#!/bin/sh
case "$#" in
  1) checker_target=$1 ;;
  *) exit 64 ;;
esac
shift
/usr/bin/env -i PATH=/usr/bin:/bin LC_ALL=C HOME=/dev/null TMPDIR=/tmp \
  GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null \
  GIT_ATTR_NOSYSTEM=1 GIT_PAGER=/bin/cat GIT_OPTIONAL_LOCKS=0 \
  GIT_NO_REPLACE_OBJECTS=1 GIT_TERMINAL_PROMPT=0 \
  /bin/bash --noprofile --norc -s -- "$checker_target" <<'DEVLAB_GIT_CHECKER'
set -euo pipefail
test "$#" -eq 1 || exit 64
target_input=$1

export PATH=/usr/bin:/bin
export LC_ALL=C
export HOME=/dev/null
export TMPDIR=/tmp
export GIT_CONFIG_NOSYSTEM=1
export GIT_CONFIG_GLOBAL=/dev/null
export GIT_CONFIG_SYSTEM=/dev/null
export GIT_ATTR_NOSYSTEM=1
export GIT_PAGER=/bin/cat
export GIT_OPTIONAL_LOCKS=0
export GIT_NO_REPLACE_OBJECTS=1
export GIT_TERMINAL_PROMPT=0

# DEVLAB_HISTORY_CONTRACT_BEGIN
DEVLAB_HISTORY_CONTRACT='SCHEMA|1
IDENTITY|Dev Lab|dev-lab@example.invalid
BRANCH|main
SOURCE|README.md|f35c009dec20278b5df50693da43c54ae4b8e228a173fcb9f59e1b3aea5a2dc5|0
SOURCE|config/bashrc.dev-lab|882ef7d9502cc5d8145c5f8b0321dbd17b0c7d431db9421cbe390f1f86e94e12|0
SOURCE|config/env.dev-lab|00aec1c6d894bb334bef59a03fad5d6392f0a2c1e5517cb89b788c4ad72b390a|0
SOURCE|data/access.log|1df6e34d28da0483cc1e62523acc777597ce3178a77d089bf7ffcabb4b0ab254|0
SOURCE|data/health-events.log|fe0119bfe33a541d816c33740f38b32280896ffce54bd7841985c7b1e6bd06e5|0
SOURCE|notes/linux-notes.md|e54276c7c8a2c2818aa48891030e31f7712fde6f5f42b70257c1a3e9582086dc|0
SOURCE|notes/shell-notes.md|d937ab49e62af7d2f5bbb92f457476afa2a9632a9d1c68135a30a98ffe9aed7d|0
SOURCE|output/health-report.txt|32c0404e72a9692ecac0a2877a98b8ae09fa90090c2af9dbdbc3c9da18a1cf1e|0
SOURCE|output/summary.txt|fd45eca2af0f073a58b8a6291f64804b6e5eade93aa773c6d5e49832edd65591|0
SOURCE|scripts/health-check.sh|5fa78e594202c38e9004b65fe69c0281c509b00ad7c10b0c48cfd2b383720e4f|1
SOURCE|scripts/permission-demo.sh|3f54de46ae71a2b3af65bd3aeaf9c28bbf91409abc67c87f718c16c4961445e8|1
SOURCE|scripts/report.sh|eb8bf1b36e7bd043f64665680b71d086a0a9aeb3c5b5a045fe2fb3e40bb52e37|1
COMMIT|C1|chore: establish dev-lab baseline||source|2000-01-01T00:00:01Z
CHANGE|C1|.gitignore|04950b968fe37d63b990bf4d5cb3a5b5684fd59320205c10282df38a8120fdbe|0
COMMIT|C2|docs: add git practice journal|C1|C1|2000-01-01T00:00:02Z
CHANGE|C2|notes/git-notes.md|5250834cba284fc1d9017836f1ac056432d341020531b6c484fa6da4ae1834be|0
COMMIT|C3|docs: record branch workflow|C2|C2|2000-01-01T00:00:03Z
CHANGE|C3|notes/git-notes.md|9796b2da5468c67a7b4274d063d7a9fb10b417c1a8caabc6ae10ac095047f342|0
COMMIT|C4|merge: integrate git workflow|C2,C3|C3|2000-01-01T00:00:04Z
COMMIT|C5|docs: record main troubleshooting step|C4|C4|2000-01-01T00:00:05Z
CHANGE|C5|notes/git-notes.md|91407f0b23c8f27c9baee81d07d736673c2ff49d661379e63caa0c1479cd5860|0
COMMIT|C6|docs: record branch troubleshooting step|C4|C4|2000-01-01T00:00:06Z
CHANGE|C6|notes/git-notes.md|f0aa82ddc8dad5b9f1072fc48f2b376385680a214659cb83cc596bfe03583022|0
COMMIT|C7|merge: resolve troubleshooting guide|C5,C6|C5|2000-01-01T00:00:07Z
CHANGE|C7|notes/git-notes.md|42fa2adba9c1aa31981c95e6389c452d30754840095f9dbe45317994291a2677|0
COMMIT|C8|docs: complete local git notes|C7|C7|2000-01-01T00:00:08Z
CHANGE|C8|README.md|f7afcc991b7f17de1d3b705733e94d0ceb1ede0d614e9fba7435f89390ea85ec|0
CHANGE|C8|notes/git-notes.md|ce1ca9eabafe913d81160cb7de9871f4dc9647c1568262ffe2ed353630a6a79c|0
FINAL|C8|main||'
# DEVLAB_HISTORY_CONTRACT_END

host_platform=$(/usr/bin/uname -s)
target_path=
git_path=
initial_refs=
initial_head_oid=
initial_symbolic_head=
critical_directory_identities=
GIT_CAPTURE_STDOUT=
GIT_CAPTURE_STDERR=
GIT_CAPTURE_STATUS=

declare -a BOUND_PATHS=()
declare -a BOUND_IDENTITIES=()
declare -a BOUND_KINDS=()
declare -a BOUND_HASHES=()
declare -a BOUND_MODES=()
declare -a TREE_MANIFEST=()
declare -a CONTRACT_SUBJECT=()
declare -a CONTRACT_PARENTS=()
declare -a CONTRACT_BASE=()
declare -a COMMIT_OID=()
declare -a COMMIT_TREE=()
declare -a COMMIT_PARENTS=()

die() {
  /usr/bin/printf 'git-local checker: %s\n' "$*" >&2
  exit 1
}

path_identity() {
  case "$host_platform" in
    Darwin) /usr/bin/stat -f '%d:%i' "$1" ;;
    Linux) /usr/bin/stat -c '%d:%i' "$1" ;;
    *) die "unsupported platform: $host_platform" ;;
  esac
}

path_mode() {
  case "$host_platform" in
    Darwin) /usr/bin/stat -f '%Lp' "$1" ;;
    Linux) /usr/bin/stat -c '%a' "$1" ;;
    *) die "unsupported platform: $host_platform" ;;
  esac
}

sha256_file() {
  local output digest remainder
  if [[ -x /usr/bin/sha256sum ]]; then
    output=$(/usr/bin/sha256sum "$1") || return 1
  elif [[ -x /usr/bin/shasum ]]; then
    output=$(/usr/bin/shasum -a 256 "$1") || return 1
  else
    die 'no SHA-256 utility is available'
  fi
  read -r digest remainder <<< "$output"
  /usr/bin/printf '%s\n' "$digest"
}

read_local_config() {
  /usr/bin/git \
    -c core.hooksPath=/dev/null \
    -c core.fsmonitor=false \
    -c core.pager=/bin/cat \
    -c pager.config=false \
    -c diff.external= \
    -C "$target_path" config --local --no-includes "$@"
}

git_read() {
  /usr/bin/git \
    -c core.hooksPath=/dev/null \
    -c core.fsmonitor=false \
    -c core.untrackedCache=false \
    -c core.attributesFile=/dev/null \
    -c core.excludesFile=/dev/null \
    -c core.pager=/bin/cat \
    -c pager.rev-parse=false \
    -c pager.for-each-ref=false \
    -c pager.cat-file=false \
    -c pager.ls-tree=false \
    -c pager.diff-index=false \
    -c pager.diff-files=false \
    -c pager.ls-files=false \
    -c diff.external= \
    -C "$target_path" "$@"
}

sha256_git_blob() {
  local object_id=$1 output digest remainder
  if [[ -x /usr/bin/sha256sum ]]; then
    output=$(git_read cat-file blob "$object_id" | /usr/bin/sha256sum) || return 1
  elif [[ -x /usr/bin/shasum ]]; then
    output=$(git_read cat-file blob "$object_id" | /usr/bin/shasum -a 256) || return 1
  else
    die 'no SHA-256 utility is available'
  fi
  read -r digest remainder <<< "$output"
  /usr/bin/printf '%s\n' "$digest"
}

bind_directory() {
  local absolute_path=$1 identity mode index
  [[ -d "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid directory: $absolute_path"
  identity=$(path_identity "$absolute_path") || die "cannot identify directory: $absolute_path"
  mode=$(path_mode "$absolute_path") || die "cannot read directory mode: $absolute_path"
  [[ -n "$identity" && -n "$mode" ]] || die "empty directory binding: $absolute_path"
  index=${#BOUND_PATHS[@]}
  BOUND_PATHS[$index]=$absolute_path
  BOUND_IDENTITIES[$index]=$identity
  BOUND_KINDS[$index]=directory
  BOUND_HASHES[$index]=''
  BOUND_MODES[$index]=$mode
}

bind_file() {
  local absolute_path=$1 identity digest mode index
  [[ -f "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid file: $absolute_path"
  identity=$(path_identity "$absolute_path") || die "cannot identify file: $absolute_path"
  digest=$(sha256_file "$absolute_path") || die "cannot hash file: $absolute_path"
  mode=$(path_mode "$absolute_path") || die "cannot read file mode: $absolute_path"
  [[ -n "$identity" && -n "$digest" && -n "$mode" ]] || die "empty file binding: $absolute_path"
  index=${#BOUND_PATHS[@]}
  BOUND_PATHS[$index]=$absolute_path
  BOUND_IDENTITIES[$index]=$identity
  BOUND_KINDS[$index]=file
  BOUND_HASHES[$index]=$digest
  BOUND_MODES[$index]=$mode
}

assert_bound_resources() {
  local index absolute_path kind identity digest mode
  for ((index = 0; index < ${#BOUND_PATHS[@]}; index += 1)); do
    absolute_path=${BOUND_PATHS[$index]}
    kind=${BOUND_KINDS[$index]}
    case "$kind" in
      directory) [[ -d "$absolute_path" && ! -L "$absolute_path" ]] || die "directory changed type: $absolute_path" ;;
      file) [[ -f "$absolute_path" && ! -L "$absolute_path" ]] || die "file changed type: $absolute_path" ;;
      *) die "unknown bound kind: $absolute_path" ;;
    esac
    identity=$(path_identity "$absolute_path") || die "cannot re-identify path: $absolute_path"
    [[ "$identity" == "${BOUND_IDENTITIES[$index]}" ]] || die "path identity changed: $absolute_path"
    mode=$(path_mode "$absolute_path") || die "cannot re-read path mode: $absolute_path"
    [[ "$mode" == "${BOUND_MODES[$index]}" ]] || die "path mode changed: $absolute_path"
    if [[ "$kind" == file ]]; then
      digest=$(sha256_file "$absolute_path") || die "cannot re-hash file: $absolute_path"
      [[ "$digest" == "${BOUND_HASHES[$index]}" ]] || die "file bytes changed: $absolute_path"
    fi
  done
}

reject_indirection_path() {
  local absolute_path=$1 label=$2
  [[ ! -e "$absolute_path" && ! -L "$absolute_path" ]] || die "$label is not allowed"
}

verify_canonical_ref_namespace() {
  local listing absolute_path relative_path entry_count=0 head_contents head_size main_contents main_size lock_path
  [[ -d "$git_path/refs" && ! -L "$git_path/refs" ]] || die 'refs must be a real directory'
  listing=$(/usr/bin/find -P "$git_path/refs" -mindepth 1 -print) || die 'cannot enumerate loose refs'
  while IFS= read -r absolute_path; do
    [[ -n "$absolute_path" && "$absolute_path" == "$git_path/refs/"* ]] || die 'invalid loose ref enumeration result'
    relative_path=${absolute_path#"$git_path/"}
    case "$relative_path" in
      refs/heads|refs/tags)
        [[ -d "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid canonical refs directory: $relative_path"
        ;;
      refs/heads/main)
        [[ -f "$absolute_path" && ! -L "$absolute_path" ]] || die 'main must be one real loose ref file'
        ;;
      *) die "unexpected loose ref path: $relative_path" ;;
    esac
    entry_count=$((entry_count + 1))
  done <<< "$listing"
  [[ "$entry_count" -eq 3 ]] || die 'loose refs must contain only heads/main and the empty tags directory'

  [[ -f "$git_path/HEAD" && ! -L "$git_path/HEAD" ]] || die 'HEAD must be one real file'
  head_contents=$(<"$git_path/HEAD") || die 'cannot read HEAD'
  head_size=$(/usr/bin/wc -c < "$git_path/HEAD") || die 'cannot size HEAD'
  read -r head_size <<< "$head_size"
  [[ "$head_contents" == 'ref: refs/heads/main' && "$head_size" -eq 21 ]] \
    || die 'HEAD must contain exactly ref: refs/heads/main plus one newline'
  main_contents=$(<"$git_path/refs/heads/main") || die 'cannot read loose main ref'
  main_size=$(/usr/bin/wc -c < "$git_path/refs/heads/main") || die 'cannot size loose main ref'
  read -r main_size <<< "$main_size"
  [[ "$main_size" -eq 41 && "$main_contents" =~ ^[0-9a-f]{40}$ ]] || die 'main loose ref has non-canonical bytes'
  if [[ -n "$initial_head_oid" ]]; then
    [[ "$main_contents" == "$initial_head_oid" ]] || die 'main loose ref changed during check'
  fi

  lock_path=$(/usr/bin/find -P "$git_path" -name '*.lock' -print -quit) || die 'cannot inspect lock files'
  [[ -z "$lock_path" ]] || die "lock file is not allowed: ${lock_path#"$git_path/"}"
}

verify_canonical_git_layout() {
  local listing absolute_path relative_path entry_count=0 logs_count=0
  local commit_message commit_message_size orig_head orig_head_size
  listing=$(/usr/bin/find -P "$git_path" -mindepth 1 -maxdepth 1 -print) || die 'cannot enumerate .git top-level layout'
  while IFS= read -r absolute_path; do
    [[ -n "$absolute_path" && "$absolute_path" == "$git_path/"* ]] || die 'invalid .git top-level enumeration result'
    relative_path=${absolute_path#"$git_path/"}
    case "$relative_path" in
      HEAD|config|index|COMMIT_EDITMSG|ORIG_HEAD)
        [[ -f "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid canonical Git control file: $relative_path"
        ;;
      logs|objects|refs)
        [[ -d "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid canonical Git control directory: $relative_path"
        ;;
      *) die "unexpected .git top-level path: $relative_path" ;;
    esac
    entry_count=$((entry_count + 1))
  done <<< "$listing"
  [[ "$entry_count" -eq 8 ]] || die '.git top-level layout is incomplete'

  commit_message=$(<"$git_path/COMMIT_EDITMSG") || die 'cannot read COMMIT_EDITMSG'
  commit_message_size=$(/usr/bin/wc -c < "$git_path/COMMIT_EDITMSG") || die 'cannot size COMMIT_EDITMSG'
  read -r commit_message_size <<< "$commit_message_size"
  [[ "$commit_message" == 'docs: complete local git notes' && "$commit_message_size" -eq 31 ]] \
    || die 'COMMIT_EDITMSG is not the canonical final message'

  orig_head=$(<"$git_path/ORIG_HEAD") || die 'cannot read ORIG_HEAD'
  orig_head_size=$(/usr/bin/wc -c < "$git_path/ORIG_HEAD") || die 'cannot size ORIG_HEAD'
  read -r orig_head_size <<< "$orig_head_size"
  [[ "$orig_head_size" -eq 41 && "$orig_head" =~ ^[0-9a-f]{40}$ ]] || die 'ORIG_HEAD has non-canonical bytes'
  if [[ -n "${COMMIT_OID[5]:-}" ]]; then
    [[ "$orig_head" == "${COMMIT_OID[5]}" ]] || die 'ORIG_HEAD must identify logical C5'
  fi

  listing=$(/usr/bin/find -P "$git_path/logs" -mindepth 1 -print) || die 'cannot enumerate reflog layout'
  while IFS= read -r absolute_path; do
    [[ -n "$absolute_path" && "$absolute_path" == "$git_path/logs/"* ]] || die 'invalid reflog enumeration result'
    relative_path=${absolute_path#"$git_path/"}
    case "$relative_path" in
      logs/refs|logs/refs/heads)
        [[ -d "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid canonical reflog directory: $relative_path"
        ;;
      logs/HEAD|logs/refs/heads/main)
        [[ -s "$absolute_path" && -f "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid canonical reflog file: $relative_path"
        ;;
      *) die "unexpected reflog path: $relative_path" ;;
    esac
    logs_count=$((logs_count + 1))
  done <<< "$listing"
  [[ "$logs_count" -eq 4 ]] || die 'reflog layout is incomplete'
}

critical_directory_state() {
  case "$host_platform" in
    Darwin) /usr/bin/stat -f '%d:%i:%HT' \
      "$target_path" "$git_path" "$git_path/objects" "$git_path/objects/info" "$git_path/objects/pack" \
      "$git_path/refs" "$git_path/refs/heads" "$git_path/refs/tags" ;;
    Linux) /usr/bin/stat -c '%d:%i:%F' \
      "$target_path" "$git_path" "$git_path/objects" "$git_path/objects/info" "$git_path/objects/pack" \
      "$git_path/refs" "$git_path/refs/heads" "$git_path/refs/tags" ;;
    *) die "unsupported platform: $host_platform" ;;
  esac
}

assert_critical_repository_directories() {
  local absolute_path current_identities
  for absolute_path in \
    "$target_path" "$git_path" "$git_path/objects" "$git_path/objects/info" "$git_path/objects/pack" \
    "$git_path/refs" "$git_path/refs/heads" "$git_path/refs/tags"; do
    [[ -d "$absolute_path" && ! -L "$absolute_path" ]] || die "critical repository directory changed type: $absolute_path"
  done
  current_identities=$(critical_directory_state) || die 'cannot identify critical repository directories'
  [[ -n "$critical_directory_identities" && "$current_identities" == "$critical_directory_identities" ]] \
    || die 'critical repository directory identity changed'
}

verify_negative_repository_state() {
  local state_path
  assert_critical_repository_directories
  reject_indirection_path "$git_path/commondir" 'commondir'
  reject_indirection_path "$git_path/config.worktree" 'worktree config'
  reject_indirection_path "$git_path/worktrees" 'linked worktree metadata'
  reject_indirection_path "$git_path/objects/info/alternates" 'object alternates'
  reject_indirection_path "$git_path/objects/info/http-alternates" 'HTTP object alternates'
  reject_indirection_path "$git_path/shallow" 'shallow boundary'
  reject_indirection_path "$git_path/info/grafts" 'grafts file'
  reject_indirection_path "$git_path/packed-refs" 'packed refs'
  for state_path in \
    MERGE_HEAD REBASE_HEAD rebase-merge rebase-apply CHERRY_PICK_HEAD REVERT_HEAD \
    BISECT_LOG BISECT_START BISECT_NAMES BISECT_EXPECTED_REV BISECT_ANCESTORS_OK \
    BISECT_HEAD BISECT_TERMS MERGE_AUTOSTASH REBASE_AUTOSTASH \
    AUTO_MERGE sequencer MERGE_RR SQUASH_MSG FETCH_HEAD; do
    reject_indirection_path "$git_path/$state_path" "in-progress state $state_path"
  done
  verify_canonical_git_layout
  verify_canonical_ref_namespace
}

capture_git_read() {
  local stdout_status stderr_status
  verify_negative_repository_state
  set +e
  GIT_CAPTURE_STDOUT=$(git_read "$@" 2>/dev/null)
  stdout_status=$?
  GIT_CAPTURE_STDERR=$(git_read "$@" 2>&1 >/dev/null)
  stderr_status=$?
  set -e
  verify_negative_repository_state
  [[ "$stdout_status" -eq "$stderr_status" ]] || die "Git read status changed between bounded passes: $1"
  GIT_CAPTURE_STATUS=$stdout_status
}

resolve_and_bind_root() {
  local physical_path
  [[ -n "$target_input" ]] || die 'repository path is empty'
  [[ -d "$target_input" && ! -L "$target_input" ]] || die 'repository root must be a real directory'
  physical_path=$(cd -- "$target_input" && pwd -P) || die 'cannot resolve physical repository root'
  [[ "$physical_path" != / ]] || die 'repository root cannot be /'
  target_path=$physical_path
  git_path="$target_path/.git"
  [[ -d "$git_path" && ! -L "$git_path" ]] || die '.git must be a real directory, not a gitfile or link'

  bind_directory "$target_path"
  bind_directory "$git_path"
  bind_directory "$git_path/objects"
  bind_directory "$git_path/objects/info"
  bind_directory "$git_path/objects/pack"
  bind_directory "$git_path/refs"
  bind_directory "$git_path/refs/heads"
  bind_directory "$git_path/refs/tags"
  bind_directory "$git_path/logs"
  bind_directory "$git_path/logs/refs"
  bind_directory "$git_path/logs/refs/heads"
  bind_file "$git_path/config"
  bind_file "$git_path/HEAD"
  bind_file "$git_path/index"
  critical_directory_identities=$(critical_directory_state) || die 'cannot bind critical repository directories'
  verify_negative_repository_state
  bind_file "$git_path/refs/heads/main"
  bind_file "$git_path/logs/HEAD"
  bind_file "$git_path/logs/refs/heads/main"
  bind_file "$git_path/ORIG_HEAD"
  bind_file "$git_path/COMMIT_EDITMSG"
}

config_value() {
  local key=$1 value
  value=$(read_local_config --get-all "$key") || die "missing local config: $key"
  [[ "$value" != *$'\n'* ]] || die "duplicate local config: $key"
  /usr/bin/printf '%s\n' "$value"
}

config_key_count() {
  local config_names=$1 expected_key=$2 config_name count=0
  while IFS= read -r config_name; do
    [[ "$config_name" == "$expected_key" ]] && count=$((count + 1))
  done <<< "$config_names"
  /usr/bin/printf '%s\n' "$count"
}

verify_local_config() {
  local config_names config_name required_key optional_key value key_count
  if read_local_config --get-all core.worktree >/dev/null 2>&1; then
    die 'core.worktree is not allowed'
  fi
  config_names=$(read_local_config --name-only --list) || die 'cannot read local config'
  [[ -n "$config_names" ]] || die 'local config is empty'
  while IFS= read -r config_name; do
    [[ -n "$config_name" ]] || die 'empty local config key'
    case "$config_name" in
      core.repositoryformatversion|core.filemode|core.bare|core.logallrefupdates|core.ignorecase|core.precomposeunicode|core.hookspath|core.fsmonitor|user.name|user.email) ;;
      include.*|includeif.*) die "config include is not allowed: $config_name" ;;
      *) die "local config key is not allowed: $config_name" ;;
    esac
  done <<< "$config_names"

  for required_key in core.repositoryformatversion core.filemode core.bare core.logallrefupdates core.hookspath core.fsmonitor user.name user.email; do
    key_count=$(config_key_count "$config_names" "$required_key")
    [[ "$key_count" -eq 1 ]] || die "local config must contain one $required_key"
  done
  [[ "$(config_value core.repositoryformatversion)" == 0 ]] || die 'wrong core.repositoryformatversion'
  case "$(config_value core.filemode)" in true|false) ;; *) die 'wrong core.filemode' ;; esac
  [[ "$(config_value core.bare)" == false ]] || die 'wrong core.bare'
  [[ "$(config_value core.logallrefupdates)" == true ]] || die 'wrong core.logallrefupdates'
  [[ "$(config_value core.hookspath)" == /dev/null ]] || die 'wrong core.hooksPath'
  [[ "$(config_value core.fsmonitor)" == false ]] || die 'wrong core.fsmonitor'
  [[ "$(config_value user.name)" == 'Dev Lab' ]] || die 'wrong user.name'
  [[ "$(config_value user.email)" == 'dev-lab@example.invalid' ]] || die 'wrong user.email'
  for optional_key in core.ignorecase core.precomposeunicode; do
    key_count=$(config_key_count "$config_names" "$optional_key")
    case "$key_count" in
      0) ;;
      1)
        value=$(config_value "$optional_key")
        case "$value" in true|false) ;; *) die "wrong $optional_key" ;; esac
        ;;
      *) die "duplicate local config: $optional_key" ;;
    esac
  done
}

reject_in_progress_state() {
  verify_negative_repository_state
}

append_tree_entry() {
  local tree_index=$1 relative_path=$2 expected_hash=$3 expected_executable=$4 manifest
  manifest=${TREE_MANIFEST[$tree_index]:-}
  TREE_MANIFEST[$tree_index]="${manifest}${manifest:+$'\n'}${relative_path}|${expected_hash}|${expected_executable}"
}

replace_tree_entry() {
  local tree_index=$1 relative_path=$2 expected_hash=$3 expected_executable=$4 manifest line path_field output='' replaced=0
  manifest=${TREE_MANIFEST[$tree_index]:-}
  while IFS= read -r line; do
    [[ -n "$line" ]] || continue
    path_field=${line%%|*}
    if [[ "$path_field" == "$relative_path" ]]; then
      [[ "$replaced" -eq 0 ]] || die "duplicate embedded tree path: $relative_path"
      line="${relative_path}|${expected_hash}|${expected_executable}"
      replaced=1
    fi
    output="${output}${output:+$'\n'}${line}"
  done <<< "$manifest"
  if [[ "$replaced" -eq 0 ]]; then
    output="${output}${output:+$'\n'}${relative_path}|${expected_hash}|${expected_executable}"
  fi
  TREE_MANIFEST[$tree_index]=$output
}

tree_contract_value() {
  local tree_index=$1 expected_path=$2 manifest line path_field found=''
  manifest=${TREE_MANIFEST[$tree_index]:-}
  while IFS= read -r line; do
    [[ -n "$line" ]] || continue
    path_field=${line%%|*}
    if [[ "$path_field" == "$expected_path" ]]; then
      [[ -z "$found" ]] || return 1
      found=${line#*|}
    fi
  done <<< "$manifest"
  [[ -n "$found" ]] || return 1
  /usr/bin/printf '%s\n' "$found"
}

tree_contract_count() {
  local tree_index=$1 manifest line count=0
  manifest=${TREE_MANIFEST[$tree_index]:-}
  while IFS= read -r line; do
    [[ -n "$line" ]] && count=$((count + 1))
  done <<< "$manifest"
  /usr/bin/printf '%s\n' "$count"
}

list_contains_line() {
  local list=$1 expected=$2 line
  while IFS= read -r line; do
    [[ "$line" == "$expected" ]] && return 0
  done <<< "$list"
  return 1
}

load_history_contract() {
  local kind field1 field2 field3 field4 field5 commit_index base_index
  TREE_MANIFEST[0]=''
  while IFS='|' read -r kind field1 field2 field3 field4 field5; do
    case "$kind" in
      SCHEMA) [[ "$field1" == 1 ]] || die 'unsupported embedded history schema' ;;
      IDENTITY) [[ "$field1" == 'Dev Lab' && "$field2" == 'dev-lab@example.invalid' ]] || die 'wrong embedded identity' ;;
      BRANCH) [[ "$field1" == main ]] || die 'wrong embedded branch' ;;
      SOURCE) append_tree_entry 0 "$field1" "$field2" "$field3" ;;
      COMMIT)
        [[ "$field1" =~ ^C[1-8]$ ]] || die "invalid embedded commit ID: $field1"
        commit_index=${field1#C}
        case "$field4" in
          source) base_index=0 ;;
          C[1-7]) base_index=${field4#C} ;;
          *) die "invalid embedded tree base: $field4" ;;
        esac
        CONTRACT_SUBJECT[$commit_index]=$field2
        CONTRACT_PARENTS[$commit_index]=$field3
        CONTRACT_BASE[$commit_index]=$field4
        TREE_MANIFEST[$commit_index]=${TREE_MANIFEST[$base_index]:-}
        ;;
      CHANGE)
        [[ "$field1" =~ ^C[1-8]$ ]] || die "invalid embedded change ID: $field1"
        replace_tree_entry "${field1#C}" "$field2" "$field3" "$field4"
        ;;
      FINAL) [[ "$field1" == C8 && "$field2" == main && -z "$field3" && -z "$field4" ]] || die 'wrong embedded final refs' ;;
      *) die "unknown embedded history record: $kind" ;;
    esac
  done <<< "$DEVLAB_HISTORY_CONTRACT"

  for commit_index in 1 2 3 4 5 6 7 8; do
    [[ -n "${CONTRACT_SUBJECT[$commit_index]:-}" && -n "${CONTRACT_BASE[$commit_index]:-}" ]] || die "incomplete embedded commit: C$commit_index"
  done
}

parse_commit() {
  local logical_id=$1 object_id=$2 logical_index=${1#C} content line header=1 subject_seen=0 tree_oid='' author_line='' committer_line='' subject=''
  local author_tail committer_tail resolved_tree parent_id parents_joined=''
  [[ "$object_id" =~ ^[0-9a-f]{40,64}$ ]] || die "invalid object ID for $logical_id"
  verify_negative_repository_state
  content=$(git_read cat-file commit "$object_id") || die "cannot read commit $logical_id"
  while IFS= read -r line || [[ -n "$line" ]]; do
    if [[ "$header" -eq 1 ]]; then
      case "$line" in
        tree\ *) [[ -z "$tree_oid" ]] || die "duplicate tree header in $logical_id"; tree_oid=${line#tree } ;;
        parent\ *)
          parent_id=${line#parent }
          [[ "$parent_id" =~ ^[0-9a-f]{40,64}$ ]] || die "invalid parent object for $logical_id"
          parents_joined="${parents_joined}${parents_joined:+ }${parent_id}"
          ;;
        author\ *) [[ -z "$author_line" ]] || die "duplicate author in $logical_id"; author_line=$line ;;
        committer\ *) [[ -z "$committer_line" ]] || die "duplicate committer in $logical_id"; committer_line=$line ;;
        '') header=0 ;;
        *) die "unexpected commit header in $logical_id" ;;
      esac
    elif [[ "$subject_seen" -eq 0 ]]; then
      subject=$line
      subject_seen=1
    fi
  done <<< "$content"

  [[ -n "$tree_oid" && "$tree_oid" =~ ^[0-9a-f]{40,64}$ ]] || die "invalid tree in $logical_id"
  [[ "$subject_seen" -eq 1 && "$subject" == "${CONTRACT_SUBJECT[$logical_index]}" ]] || die "wrong subject for $logical_id"
  [[ "$author_line" == 'author Dev Lab <dev-lab@example.invalid> '* ]] || die "wrong author identity for $logical_id"
  [[ "$committer_line" == 'committer Dev Lab <dev-lab@example.invalid> '* ]] || die "wrong committer identity for $logical_id"
  author_tail=${author_line#'author Dev Lab <dev-lab@example.invalid> '}
  committer_tail=${committer_line#'committer Dev Lab <dev-lab@example.invalid> '}
  [[ "$author_tail" =~ ^[0-9]+\ [+-][0-9]{4}$ ]] || die "invalid author timestamp form for $logical_id"
  [[ "$committer_tail" =~ ^[0-9]+\ [+-][0-9]{4}$ ]] || die "invalid committer timestamp form for $logical_id"
  resolved_tree=$(git_read rev-parse --verify "$object_id^{tree}") || die "cannot resolve tree for $logical_id"
  verify_negative_repository_state
  [[ "$resolved_tree" == "$tree_oid" ]] || die "tree header mismatch for $logical_id"

  COMMIT_OID[$logical_index]=$object_id
  COMMIT_TREE[$logical_index]=$tree_oid
  COMMIT_PARENTS[$logical_index]=$parents_joined
}

first_parent() {
  local logical_id=$1 logical_index=${1#C}
  local -a parents=()
  read -r -a parents <<< "${COMMIT_PARENTS[$logical_index]}"
  [[ "${#parents[@]}" -ge 1 ]] || die "missing first parent for $logical_id"
  /usr/bin/printf '%s\n' "${parents[0]}"
}

second_parent() {
  local logical_id=$1 logical_index=${1#C}
  local -a parents=()
  read -r -a parents <<< "${COMMIT_PARENTS[$logical_index]}"
  [[ "${#parents[@]}" -eq 2 ]] || die "$logical_id must have two parents"
  /usr/bin/printf '%s\n' "${parents[1]}"
}

verify_parent_graph() {
  local logical_index expected_ids expected_oids parent_id parent_index actual_oids object_id seen_objects='' old_ifs
  for logical_index in 1 2 3 4 5 6 7 8; do
    object_id=${COMMIT_OID[$logical_index]}
    list_contains_line "$seen_objects" "$object_id" && die "duplicate logical commit object: C$logical_index"
    seen_objects="${seen_objects}${seen_objects:+$'\n'}${object_id}"
    expected_ids=${CONTRACT_PARENTS[$logical_index]}
    expected_oids=''
    if [[ -n "$expected_ids" ]]; then
      old_ifs=$IFS
      IFS=,
      set -- $expected_ids
      IFS=$old_ifs
      for parent_id in "$@"; do
        parent_index=${parent_id#C}
        [[ -n "${COMMIT_OID[$parent_index]:-}" ]] || die "missing logical parent $parent_id"
        expected_oids="${expected_oids}${expected_oids:+ }${COMMIT_OID[$parent_index]}"
      done
    fi
    actual_oids=${COMMIT_PARENTS[$logical_index]}
    [[ "$actual_oids" == "$expected_oids" ]] || die "wrong parent order for C$logical_index"
  done
}

discover_history() {
  local c7_oid c5_oid c6_oid c4_oid c2_oid c3_oid c1_oid
  verify_negative_repository_state
  parse_commit C8 "$initial_head_oid"
  c7_oid=$(first_parent C8)
  parse_commit C7 "$c7_oid"
  c5_oid=$(first_parent C7)
  c6_oid=$(second_parent C7)
  parse_commit C5 "$c5_oid"
  parse_commit C6 "$c6_oid"
  c4_oid=$(first_parent C5)
  parse_commit C4 "$c4_oid"
  c2_oid=$(first_parent C4)
  c3_oid=$(second_parent C4)
  parse_commit C2 "$c2_oid"
  parse_commit C3 "$c3_oid"
  c1_oid=$(first_parent C2)
  parse_commit C1 "$c1_oid"
  verify_parent_graph
  verify_negative_repository_state
}

verify_commit_tree() {
  local logical_id=$1 logical_index=${1#C} object_id listing line metadata relative_path mode object_type blob_id extra
  local expected_value expected_hash expected_executable actual_hash expected_count actual_count=0 seen_paths=''
  object_id=${COMMIT_OID[$logical_index]}
  verify_negative_repository_state
  listing=$(git_read ls-tree -r --full-tree "$object_id") || die "cannot list tree for $logical_id"
  while IFS= read -r line; do
    [[ -n "$line" ]] || continue
    [[ "$line" == *$'\t'* ]] || die "invalid tree entry in $logical_id"
    metadata=${line%%$'\t'*}
    relative_path=${line#*$'\t'}
    read -r mode object_type blob_id extra <<< "$metadata"
    [[ -z "${extra:-}" && "$object_type" == blob && "$blob_id" =~ ^[0-9a-f]{40,64}$ ]] || die "invalid tree metadata in $logical_id"
    expected_value=$(tree_contract_value "$logical_index" "$relative_path") || die "unexpected tree path in $logical_id: $relative_path"
    list_contains_line "$seen_paths" "$relative_path" && die "duplicate tree path in $logical_id: $relative_path"
    seen_paths="${seen_paths}${seen_paths:+$'\n'}${relative_path}"
    expected_hash=${expected_value%%|*}
    expected_executable=${expected_value##*|}
    case "$expected_executable" in
      0) [[ "$mode" == 100644 ]] || die "wrong tree mode in $logical_id: $relative_path" ;;
      1) [[ "$mode" == 100755 ]] || die "wrong tree mode in $logical_id: $relative_path" ;;
      *) die "invalid embedded mode for $logical_id: $relative_path" ;;
    esac
    actual_hash=$(sha256_git_blob "$blob_id") || die "cannot hash blob in $logical_id: $relative_path"
    [[ "$actual_hash" == "$expected_hash" ]] || die "wrong blob bytes in $logical_id: $relative_path"
    actual_count=$((actual_count + 1))
  done <<< "$listing"

  expected_count=$(tree_contract_count "$logical_index")
  [[ "$actual_count" -eq "$expected_count" ]] || die "wrong tree path count in $logical_id"
  verify_negative_repository_state
}

verify_all_commit_trees() {
  local logical_id
  verify_negative_repository_state
  for logical_id in C1 C2 C3 C4 C5 C6 C7 C8; do
    verify_commit_tree "$logical_id"
  done
  verify_negative_repository_state
}

verify_disk_file() {
  local absolute_path=$1 relative_path=$2 bind_now=$3 expected_value expected_hash expected_executable actual_hash
  expected_value=$(tree_contract_value 8 "$relative_path") || die "unexpected final file: $relative_path"
  [[ -f "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid final file: $relative_path"
  expected_hash=${expected_value%%|*}
  expected_executable=${expected_value##*|}
  actual_hash=$(sha256_file "$absolute_path") || die "cannot hash final file: $relative_path"
  [[ "$actual_hash" == "$expected_hash" ]] || die "wrong final bytes: $relative_path"
  case "$expected_executable" in
    0) [[ ! -x "$absolute_path" ]] || die "unexpected final executable mode: $relative_path" ;;
    1) [[ -x "$absolute_path" ]] || die "missing final executable mode: $relative_path" ;;
    *) die "invalid final mode contract: $relative_path" ;;
  esac
  if [[ "$bind_now" == 1 ]]; then
    bind_file "$absolute_path"
  fi
}

verify_disk_snapshot() {
  local bind_now=$1 listing absolute_path relative_path entry_count=0 expected_count
  listing=$(/usr/bin/find -P "$target_path" -mindepth 1 \( -path "$git_path" -o -path "$git_path/*" \) -prune -o -print) || die 'cannot enumerate final worktree'
  while IFS= read -r absolute_path; do
    [[ -n "$absolute_path" && "$absolute_path" == "$target_path/"* ]] || die 'invalid worktree enumeration result'
    relative_path=${absolute_path#"$target_path/"}
    case "$relative_path" in
      config|data|notes|output|scripts)
        [[ -d "$absolute_path" && ! -L "$absolute_path" ]] || die "invalid final directory: $relative_path"
        if [[ "$bind_now" == 1 ]]; then bind_directory "$absolute_path"; fi
        ;;
      *) verify_disk_file "$absolute_path" "$relative_path" "$bind_now" ;;
    esac
    entry_count=$((entry_count + 1))
  done <<< "$listing"
  expected_count=$(tree_contract_count 8)
  expected_count=$((expected_count + 5))
  [[ "$entry_count" -eq "$expected_count" ]] || die 'final worktree has missing or extra paths'
}

verify_refs_and_head() {
  local replace_refs ref_listing symbolic_head head_oid
  capture_git_read for-each-ref --format='%(refname)' refs/replace
  [[ "$GIT_CAPTURE_STATUS" -eq 0 ]] || die 'cannot inspect replace refs'
  [[ -z "$GIT_CAPTURE_STDERR" ]] || die "Git emitted diagnostics while inspecting replace refs: $GIT_CAPTURE_STDERR"
  replace_refs=$GIT_CAPTURE_STDOUT
  [[ -z "$replace_refs" ]] || die 'replace refs are not allowed'
  capture_git_read for-each-ref --format='%(refname)|%(objectname)|%(objecttype)' refs
  [[ "$GIT_CAPTURE_STATUS" -eq 0 ]] || die 'cannot inspect refs'
  [[ -z "$GIT_CAPTURE_STDERR" ]] || die "Git emitted diagnostics while inspecting refs: $GIT_CAPTURE_STDERR"
  ref_listing=$GIT_CAPTURE_STDOUT
  [[ "$ref_listing" =~ ^refs/heads/main\|[0-9a-f]{40,64}\|commit$ ]] || die 'only refs/heads/main is allowed'
  capture_git_read rev-parse --symbolic-full-name HEAD
  [[ "$GIT_CAPTURE_STATUS" -eq 0 ]] || die 'cannot inspect symbolic HEAD'
  [[ -z "$GIT_CAPTURE_STDERR" ]] || die "Git emitted diagnostics while inspecting symbolic HEAD: $GIT_CAPTURE_STDERR"
  symbolic_head=$GIT_CAPTURE_STDOUT
  [[ "$symbolic_head" == refs/heads/main ]] || die 'HEAD must point to refs/heads/main'
  capture_git_read rev-parse --verify 'refs/heads/main^{commit}'
  [[ "$GIT_CAPTURE_STATUS" -eq 0 ]] || die 'cannot resolve main commit'
  [[ -z "$GIT_CAPTURE_STDERR" ]] || die "Git emitted diagnostics while resolving main: $GIT_CAPTURE_STDERR"
  head_oid=$GIT_CAPTURE_STDOUT
  [[ "$ref_listing" == "refs/heads/main|$head_oid|commit" ]] || die 'main ref changed while reading'
  initial_refs=$ref_listing
  initial_symbolic_head=$symbolic_head
  initial_head_oid=$head_oid
}

verify_clean_state() {
  local untracked diff_files_status
  verify_negative_repository_state
  if git_read diff-index --quiet --cached --no-ext-diff --no-textconv "$initial_head_oid" --; then :; else
    die 'index differs from HEAD'
  fi
  if git_read diff-files --quiet --no-ext-diff --no-textconv --; then
    diff_files_status=0
  else
    diff_files_status=$?
  fi
  # A byte-for-byte copied repository can retain stale index stat data. Status 1 is
  # resolved below by the exact C8 disk manifest without refreshing the index.
  [[ "$diff_files_status" -eq 0 || "$diff_files_status" -eq 1 ]] || die 'cannot compare worktree with index'
  untracked=$(git_read ls-files --others --) || die 'cannot inspect untracked paths'
  [[ -z "$untracked" ]] || die "untracked path is not allowed: ${untracked%%$'\n'*}"
  verify_negative_repository_state
}

verify_index_state() {
  local index_listing tree_listing entry ctime_line mtime_line device_line ownership_line size_line
  local entry_pattern ctime_pattern mtime_pattern device_pattern ownership_pattern size_pattern mode object_id stage relative_path
  local normalized='' actual_count=0 expected_count
  entry_pattern='^(100644|100755) ([0-9a-f]{40}) ([0-3])'$'\t''(.+)$'
  ctime_pattern='^  ctime: [0-9]+:[0-9]+$'
  mtime_pattern='^  mtime: [0-9]+:[0-9]+$'
  device_pattern='^  dev: [0-9]+'$'\t''ino: [0-9]+$'
  ownership_pattern='^  uid: [0-9]+'$'\t''gid: [0-9]+$'
  size_pattern='^  size: [0-9]+'$'\t''flags: 0$'

  verify_negative_repository_state
  index_listing=$(git_read ls-files --stage --debug --) || die 'cannot inspect index entries'
  while IFS= read -r entry; do
    [[ "$entry" =~ $entry_pattern ]] || die 'invalid index entry metadata'
    mode=${BASH_REMATCH[1]}
    object_id=${BASH_REMATCH[2]}
    stage=${BASH_REMATCH[3]}
    relative_path=${BASH_REMATCH[4]}
    [[ "$stage" == 0 ]] || die "non-stage-zero index entry is not allowed: $relative_path"
    IFS= read -r ctime_line || die "missing index ctime: $relative_path"
    IFS= read -r mtime_line || die "missing index mtime: $relative_path"
    IFS= read -r device_line || die "missing index device metadata: $relative_path"
    IFS= read -r ownership_line || die "missing index ownership metadata: $relative_path"
    IFS= read -r size_line || die "missing index flags: $relative_path"
    [[ "$ctime_line" =~ $ctime_pattern ]] || die "invalid index ctime: $relative_path"
    [[ "$mtime_line" =~ $mtime_pattern ]] || die "invalid index mtime: $relative_path"
    [[ "$device_line" =~ $device_pattern ]] || die "invalid index device metadata: $relative_path"
    [[ "$ownership_line" =~ $ownership_pattern ]] || die "invalid index ownership metadata: $relative_path"
    [[ "$size_line" =~ $size_pattern ]] || die "non-canonical index flags: $relative_path"
    normalized="${normalized}${normalized:+$'\n'}${mode} blob ${object_id}"$'\t'"${relative_path}"
    actual_count=$((actual_count + 1))
  done <<< "$index_listing"

  expected_count=$(tree_contract_count 8)
  [[ "$actual_count" -eq "$expected_count" ]] || die 'index path count differs from C8'
  tree_listing=$(git_read ls-tree -r --full-tree "$initial_head_oid") || die 'cannot inspect C8 tree for index comparison'
  [[ "$normalized" == "$tree_listing" ]] || die 'index mode, object, stage, or path differs from C8'
  verify_negative_repository_state
}

verify_final_stability() {
  local final_refs final_symbolic_head final_head_oid
  verify_negative_repository_state
  verify_local_config
  verify_negative_repository_state
  capture_git_read for-each-ref --format='%(refname)|%(objectname)|%(objecttype)' refs
  [[ "$GIT_CAPTURE_STATUS" -eq 0 ]] || die 'cannot re-inspect refs'
  [[ -z "$GIT_CAPTURE_STDERR" ]] || die "Git emitted diagnostics while re-inspecting refs: $GIT_CAPTURE_STDERR"
  final_refs=$GIT_CAPTURE_STDOUT
  capture_git_read rev-parse --symbolic-full-name HEAD
  [[ "$GIT_CAPTURE_STATUS" -eq 0 ]] || die 'cannot re-inspect symbolic HEAD'
  [[ -z "$GIT_CAPTURE_STDERR" ]] || die "Git emitted diagnostics while re-inspecting HEAD: $GIT_CAPTURE_STDERR"
  final_symbolic_head=$GIT_CAPTURE_STDOUT
  capture_git_read rev-parse --verify 'refs/heads/main^{commit}'
  [[ "$GIT_CAPTURE_STATUS" -eq 0 ]] || die 'cannot re-inspect main'
  [[ -z "$GIT_CAPTURE_STDERR" ]] || die "Git emitted diagnostics while re-inspecting main: $GIT_CAPTURE_STDERR"
  final_head_oid=$GIT_CAPTURE_STDOUT
  [[ "$final_refs" == "$initial_refs" ]] || die 'refs changed during check'
  [[ "$final_symbolic_head" == "$initial_symbolic_head" ]] || die 'HEAD changed during check'
  [[ "$final_head_oid" == "$initial_head_oid" ]] || die 'main changed during check'
  verify_clean_state
  verify_disk_snapshot 0
  discover_history
  verify_all_commit_trees
  verify_index_state
  assert_bound_resources
  verify_disk_snapshot 0
  verify_clean_state
  verify_negative_repository_state
  assert_bound_resources
}

check_git_local() {
  resolve_and_bind_root
  verify_negative_repository_state
  verify_local_config
  verify_negative_repository_state
  load_history_contract
  verify_refs_and_head
  verify_clean_state
  verify_disk_snapshot 1
  discover_history
  verify_all_commit_trees
  verify_index_state
  verify_negative_repository_state
  verify_final_stability
  verify_negative_repository_state
  assert_bound_resources
  /usr/bin/printf 'git-local checkpoint: ok\n'
}

check_git_local
DEVLAB_GIT_CHECKER
