#!/usr/bin/env bash
# gstack-context-checkpoint — single-call helper for /context-save and /context-restore.
#
# Modes:
#   save [--title <raw>] [--status <status>] [--body-file <path>]
#        [--carry-forward | --replace | --clear]
#                                              Write a lean checkpoint from stdin or --body-file,
#                                              carry forward open decisions/reversals/promises from
#                                              the prior same-branch checkpoint on stub/non-code
#                                              saves (unless --replace/--clear), auto-fill frontmatter,
#                                              stamp identity + HEAD before atomic non-overwriting
#                                              publish, and record a nested-repo pointer when
#                                              CLAUDE_PROJECT_DIR differs.
#   prep [--title <raw>]                       Compute collision-safe path, branch, duration, and
#                                              minimal modified-file list without writing.
#   stamp <file>                               Stamp project identity + HEAD on an existing file.
#   duration                                   Print SESSION_DURATION_S=<seconds|unknown>.
#   head-check <file>                          Compare checkpoint frontmatter head: with current HEAD.
#   restore [--no-read] [--fragment <q> | --fragment-stdin] [--file <path> | --file-stdin]
#                                              Discover & verify checkpoints (current branch first,
#                                              cross-branch fallback), check HEAD drift, and print
#                                              the selected checkpoint body in one call.
#   list [--all]                               List saved checkpoints (current branch or --all),
#                                              matching restore's verified candidate numbering.

BASH_COMPAT=50
set -uo pipefail

_BIN=$(cd "$(dirname "$0")" 2>/dev/null && pwd)
. "$_BIN/gstack-state-root.sh" 2>/dev/null || {
  echo "$0: cannot resolve the gstack state root: $_BIN/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2
  exit 1
}
gstack_state_root_select
GSTACK_STATE_ROOT="$_gstack_sr_root"
_TAB=$(printf '\t')

_current_branch() {
  git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --abbrev-ref HEAD 2>/dev/null || true
}

_sanitize() {
  sed -e 's/GSTACK_INSTRUCTION/GSTACK-INSTRUCTION-(stripped)/g' \
      -e 's/^SESSION_ID:/SESSION-ID-(stripped):/' \
      -e 's/^--- END CHECKPOINT ---$/--- END-CHECKPOINT-(escaped) ---/' \
      -e 's/^--- END PRIOR OPEN CONTEXT ---$/--- END-PRIOR-OPEN-CONTEXT-(escaped) ---/'
}

_require_arg() {
  if [ "$2" -lt 2 ]; then
    echo "gstack-context-checkpoint: $1 requires a value" >&2
    exit 2
  fi
}

_compute_duration() {
  local start_epoch="" lstart="" now="" target_pid="" pcomm="" gp=""
  if [ -n "${_TEL_START:-}" ]; then
    start_epoch="$_TEL_START"
  elif [ -n "${PPID:-}" ]; then
    target_pid="$PPID"
    # Walk up one level only past a shell wrapper (e.g. Bash tool subshell) to the caller session.
    pcomm=$(ps -o comm= -p "$PPID" 2>/dev/null | tr -d '[:space:]' || true)
    case "$(basename "$pcomm" 2>/dev/null || printf '%s' "$pcomm")" in
      sh|bash|zsh|dash|ash|ksh|fish|-sh|-bash|-zsh)
        gp=$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d '[:space:]' || true)
        case "$gp" in
          ''|*[!0-9]*) ;;
          *) [ "$gp" -gt 1 ] 2>/dev/null && target_pid="$gp" ;;
        esac
        ;;
    esac
    lstart=$(ps -o lstart= -p "$target_pid" 2>/dev/null || true)
    # BSD date (macOS) parses with -jf; GNU date (Linux) with -d. Never parse an
    # empty start: GNU date -d "" means today at midnight.
    if [ -n "$lstart" ]; then
      start_epoch=$(date -jf "%c" "$lstart" "+%s" 2>/dev/null || date -d "$lstart" "+%s" 2>/dev/null || echo "")
    fi
  fi
  case "$start_epoch" in
    ''|*[!0-9]*)
      SESSION_DURATION_S="unknown"
      ;;
    *)
      now=$(date +%s)
      if [ "$now" -ge "$start_epoch" ] 2>/dev/null; then
        SESSION_DURATION_S=$((now - start_epoch))
      else
        SESSION_DURATION_S="unknown"
      fi
      ;;
  esac
}

_iso_timestamp() {
  local tz
  tz=$(date +%z 2>/dev/null || echo "+0000")
  case "$tz" in
    [+-][0-9][0-9][0-9][0-9]) tz="${tz%??}:${tz#???}" ;;
    *) tz="Z" ;;
  esac
  printf '%s%s' "$(date +%Y-%m-%dT%H:%M:%S)" "$tz"
}

_resolve_timestamp() {
  if [ -n "${GSTACK_CHECKPOINT_TIMESTAMP:-}" ]; then
    case "$GSTACK_CHECKPOINT_TIMESTAMP" in
      *$'\n'*|*$'\r'*)
        echo "gstack-context-checkpoint: invalid GSTACK_CHECKPOINT_TIMESTAMP (expected YYYYMMDD-HHMMSS)" >&2
        exit 2
        ;;
    esac
    if [[ ! "$GSTACK_CHECKPOINT_TIMESTAMP" =~ ^[0-9]{8}-[0-9]{6}$ ]] || [ "${#GSTACK_CHECKPOINT_TIMESTAMP}" -ne 15 ]; then
      echo "gstack-context-checkpoint: invalid GSTACK_CHECKPOINT_TIMESTAMP (expected YYYYMMDD-HHMMSS)" >&2
      exit 2
    fi
    TIMESTAMP="$GSTACK_CHECKPOINT_TIMESTAMP"
  else
    TIMESTAMP=$(date +%Y%m%d-%H%M%S)
  fi
}

_compute_save_path() {
  local raw="$1"
  local force_suffix="${2:-0}"
  local ts suffix i
  TITLE_SLUG=$(printf '%s' "$raw" | tr '[:upper:]' '[:lower:]' | tr -s ' \t' '-' | tr -cd 'a-z0-9.-' | cut -c1-60)
  TITLE_SLUG="${TITLE_SLUG:-untitled}"
  _resolve_timestamp
  ts="$TIMESTAMP"
  FILE="${CHECKPOINT_DIR}/${ts}-${TITLE_SLUG}.md"
  if [ "$force_suffix" -eq 1 ] || [ -e "$FILE" ]; then
    i=0
    while [ "$i" -lt 12 ]; do
      suffix=$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom 2>/dev/null | head -c 4 || true)
      [ -n "$suffix" ] || suffix=$(printf '%04x%x' "$$" "$i")
      FILE="${CHECKPOINT_DIR}/${ts}-${TITLE_SLUG}-${suffix}.md"
      [ ! -e "$FILE" ] && break
      i=$((i + 1))
    done
    if [ -e "$FILE" ]; then
      FILE="${CHECKPOINT_DIR}/${ts}-${TITLE_SLUG}-$$-${RANDOM:-0}.md"
    fi
  fi
}

_head_status_for() {
  local target_head="$1" repo_dir="$2" current_head="$3"
  if [ "$target_head" = "$current_head" ]; then
    echo "HEAD_UNCHANGED"
  elif ! printf '%s\n' "$target_head" | grep -Eqx '[0-9a-f]{40}([0-9a-f]{24})?' \
    || ! git -C "$repo_dir" cat-file -e "${target_head}^{commit}" 2>/dev/null; then
    echo "HEAD_UNKNOWN $target_head"
  elif git -C "$repo_dir" merge-base --is-ancestor "$target_head" "$current_head" 2>/dev/null; then
    echo "HEAD_MOVED $(git -C "$repo_dir" rev-list --count "$target_head..$current_head")"
    git -C "$repo_dir" log --oneline -10 "$target_head..$current_head"
  else
    echo "HEAD_DIVERGED $target_head"
  fi
}

_checkpoint_carried_promises_head() {
  tr -d '\r' < "$1" 2>/dev/null | sed -n '1{/^---$/!q;d;}; /^---$/q; /^carried_promises_head:/{s/^carried_promises_head:[[:space:]]*//p;q;}'
}

_checkpoint_promises_head() {
  local ch
  ch=$(_checkpoint_carried_promises_head "$1")
  if [ -n "$ch" ]; then
    printf '%s' "$ch"
  else
    _checkpoint_head "$1"
  fi
}

_head_check() {
  local file="$1"
  local id_tag="${2:-}"
  local backfill_prom_head="${3:-}"
  local saved_head carried_head repo_dir current_head
  saved_head=$(tr -d '\r' < "$file" 2>/dev/null | sed -n '1{/^---$/!q;d;}; /^---$/q; /^head:/{s/^head:[[:space:]]*//p;q;}')
  carried_head=$(_checkpoint_carried_promises_head "$file")
  repo_dir=""
  if [ "$id_tag" = "BELOW" ] || ! git rev-parse --git-dir >/dev/null 2>&1; then
    repo_dir=$(tr -d '\r' < "$file" 2>/dev/null | sed -n '1{/^---$/!q;d;}; /^---$/q; /^worktree:/{s/^worktree:[[:space:]]*//p;q;}')
    [ -n "$repo_dir" ] || repo_dir=$(tr -d '\r' < "$file" 2>/dev/null | sed -n '1{/^---$/!q;d;}; /^---$/q; /^project_root:/{s/^project_root:[[:space:]]*//p;q;}')
  fi
  [ -n "$repo_dir" ] || repo_dir="."
  current_head=$(git -C "$repo_dir" rev-parse --verify -q HEAD 2>/dev/null || true)
  if [ -z "$current_head" ]; then
    if [ -z "$saved_head" ] && [ -z "$carried_head" ] && [ -z "$backfill_prom_head" ]; then
      echo "HEAD_UNTRACKED"
    else
      echo "HEAD_NOT_CHECKED"
    fi
    return 0
  fi
  if [ -z "$saved_head" ]; then
    if [ -n "$backfill_prom_head" ] && [ "$backfill_prom_head" != "$current_head" ]; then
      _head_status_for "$backfill_prom_head" "$repo_dir" "$current_head"
    elif [ -n "$carried_head" ] && [ "$carried_head" != "$current_head" ]; then
      _head_status_for "$carried_head" "$repo_dir" "$current_head"
    else
      echo "HEAD_UNTRACKED"
    fi
    return 0
  fi
  if [ "$saved_head" != "$current_head" ]; then
    _head_status_for "$saved_head" "$repo_dir" "$current_head"
    return 0
  fi
  if [ -n "$backfill_prom_head" ] && [ "$backfill_prom_head" != "$current_head" ]; then
    _head_status_for "$backfill_prom_head" "$repo_dir" "$current_head"
    return 0
  fi
  if [ -n "$carried_head" ] && [ "$carried_head" != "$current_head" ]; then
    _head_status_for "$carried_head" "$repo_dir" "$current_head"
    return 0
  fi
  echo "HEAD_UNCHANGED"
}

_checkpoint_branch() {
  tr -d '\r' < "$1" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && $0 == "---" { exit }
    fm && /^branch:/ { sub(/^branch:[ \t]*/, ""); sub(/[ \t]+$/, ""); print; exit }
  '
}

_checkpoint_title() {
  local f="$1"
  local t
  t=$(tr -d '\r' < "$f" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && $0 == "---" { fm = 0; next }
    !fm && /^## Working on:/ { sub(/^## Working on:[ \t]*/, ""); sub(/[ \t]+$/, ""); print; exit }
  ')
  if [ -z "$t" ]; then
    t=$(basename "$f" .md | sed -E 's/^[0-9]{8}-[0-9]{6}-?//')
  fi
  printf '%s' "$t"
}

_body_title() {
  tr -d '\r' < "$1" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && $0 == "---" { fm = 0; next }
    !fm && /^## Working on:/ { sub(/^## Working on:[ \t]*/, ""); sub(/[ \t]+$/, ""); print; exit }
  '
}

_norm_title() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]' \
    | sed -E 's/^[[:space:]]*[0-9]{4}-?[0-9]{2}-?[0-9]{2}([-_t ]?[0-9]{2}:?[0-9]{2}(:?[0-9]{2})?)?//; s/[[:punct:][:space:]]+/ /g; s/^ //; s/ $//'
}

_basename_ts() {
  basename "$1" .md | sed -nE 's/^([0-9]{8}-[0-9]{6}).*/\1/p'
}

_phys_path() {
  local p="$1" d
  d=$(cd "$(dirname "$p")" 2>/dev/null && pwd -P) || return 1
  printf '%s/%s' "$d" "$(basename "$p")"
}

_checkpoint_project_root() {
  tr -d '\r' < "$1" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && $0 == "---" { exit }
    fm && /^project_root:/ { sub(/^project_root:[ \t]*/, ""); sub(/[ \t]+$/, ""); print; exit }
  '
}

_is_below_cwd() {
  local f="$1" proot cwd_phys proot_phys
  proot=$(_checkpoint_project_root "$f")
  [ -n "$proot" ] || return 1
  cwd_phys=$(pwd -P 2>/dev/null || pwd)
  proot_phys=$(cd "$proot" 2>/dev/null && pwd -P) || proot_phys="$proot"
  [ "$cwd_phys" = "/" ] || cwd_phys="${cwd_phys%/}"
  [ "$proot_phys" = "/" ] || proot_phys="${proot_phys%/}"
  if [ "$cwd_phys" = "/" ]; then
    case "$proot_phys" in /*) [ "$proot_phys" != "/" ] && return 0 ;; esac
    return 1
  fi
  case "$proot_phys" in
    "$cwd_phys"/*) return 0 ;;
    *) return 1 ;;
  esac
}

_resolve_project_identity() {
  SLUG=""; PROJECT_REMOTE=""; PROJECT_ROOT=""; LEGACY_SLUG=""
  local id_out
  id_out=$("$_BIN/gstack-slug" --identity 2>/dev/null || true)
  if [ -n "$id_out" ]; then
    eval "$(printf '%s\n' "$id_out" | grep -E '^(SLUG|PROJECT_REMOTE|PROJECT_ROOT|LEGACY_SLUG)=')" 2>/dev/null || true
  fi
  SLUG="${SLUG:-unknown}"
  CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints"
}

# Populates shared verified/foreign/unverified lists in canonical order:
# current-branch checkpoints first (newest-first by filename), then other branches (newest-first).
# Used by both restore and list so 1-based numbering matches 1-to-1.
_discover_checkpoints() {
  local scan_cap="${1:-0}" # 0 = unlimited; >0 = cap newest files before branch grouping
  local same_branch_only="${2:-0}" # 1 = emit and classify only CURRENT_BRANCH files (used by save)
  VERIFIED_ALL=""
  MATCHED_ALL=""
  VERIFIED_SAME=""
  FOREIGN_LINES=""
  UNVERIFIED_LINES=""
  ROOT_DIFFERS_LINES=""
  FOREIGN_N=0
  IDENTITY_STATE="OK"
  CLASSIFIED=""
  ORDERED=""

  if [ ! -d "$CHECKPOINT_DIR" ]; then
    IDENTITY_STATE="EMPTY"
    return 0
  fi
  local all
  if [ "$scan_cap" -gt 0 ] 2>/dev/null; then
    all=$(find "$CHECKPOINT_DIR" -maxdepth 1 -name "*.md" -type f 2>/dev/null | LC_ALL=C sort -r | head -"$scan_cap")
  else
    all=$(find "$CHECKPOINT_DIR" -maxdepth 1 -name "*.md" -type f 2>/dev/null | LC_ALL=C sort -r)
  fi
  if [ -z "$all" ]; then
    IDENTITY_STATE="EMPTY"
    return 0
  fi

  CLEARED_TS_MAP=""
  ORDERED=$(printf '%s\n' "$all" | GSTACK_CUR_BR="$CURRENT_BRANCH" awk -v same_only="$same_branch_only" '
    function base_ts(path,    n, segs, bn) {
      n = split(path, segs, "/")
      bn = segs[n]
      if (bn ~ /^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]/) {
        return substr(bn, 1, 15)
      }
      return ""
    }
    function flush_grp(g_f, g_seq, g_clr, gn,    i, j, kf, ks, kc) {
      for (i = 2; i <= gn; i++) {
        kf = g_f[i]; ks = g_seq[i]; kc = g_clr[i]
        j = i - 1
        while (j >= 1 && (g_seq[j] < ks || (g_seq[j] == ks && g_clr[j] < kc))) {
          g_f[j + 1] = g_f[j]; g_seq[j + 1] = g_seq[j]; g_clr[j + 1] = g_clr[j]
          j--
        }
        g_f[j + 1] = kf; g_seq[j + 1] = ks; g_clr[j + 1] = kc
      }
      for (i = 1; i <= gn; i++) print g_f[i]
    }
    function emit_list(arr, ts_arr, seq_arr, clr_arr, n,    i, cur_ts, gn, g_f, g_seq, g_clr) {
      cur_ts = ""; gn = 0
      for (i = 1; i <= n; i++) {
        if (ts_arr[i] == "" || ts_arr[i] != cur_ts) {
          if (gn > 0) { flush_grp(g_f, g_seq, g_clr, gn); gn = 0 }
          if (ts_arr[i] == "") {
            cur_ts = ""
            print arr[i]
            continue
          }
          cur_ts = ts_arr[i]
        }
        gn++
        g_f[gn] = arr[i]; g_seq[gn] = seq_arr[i]; g_clr[gn] = clr_arr[i]
      }
      if (gn > 0) flush_grp(g_f, g_seq, g_clr, gn)
    }
    BEGIN { cur = ENVIRON["GSTACK_CUR_BR"]; ns = 0; no = 0 }
    $0 == "" { next }
    {
      f = $0; b = ""; clr = 0; seq = 0; fm = 0; ln = 0
      while ((getline line < f) > 0) {
        ln++
        sub(/\r$/, "", line)
        if (ln == 1) {
          if (line == "---") { fm = 1; continue }
          break
        }
        if (fm && line == "---") break
        if (fm && line ~ /^branch:/ && b == "") {
          sub(/^branch:[ \t]*/, "", line)
          sub(/[ \t]+$/, "", line)
          b = line
        } else if (fm && line ~ /^carry_forward:/) {
          sub(/^carry_forward:[ \t]*/, "", line)
          sub(/[ \t]+$/, "", line)
          if (tolower(line) == "cleared") clr = 1
        } else if (fm && line ~ /^save_seq:/) {
          sub(/^save_seq:[ \t]*/, "", line)
          sub(/[ \t]+$/, "", line)
          if (line ~ /^[0-9]+$/) seq = line + 0
        }
      }
      close(f)
      if (cur != "" && b == cur) {
        ns++
        same[ns] = f; same_ts[ns] = base_ts(f); same_seq[ns] = seq; same_clr[ns] = clr
      } else if (!same_only) {
        no++
        other[no] = f; other_ts[no] = base_ts(f); other_seq[no] = seq; other_clr[no] = clr
      }
    }
    END {
      emit_list(same, same_ts, same_seq, same_clr, ns)
      if (!same_only) emit_list(other, other_ts, other_seq, other_clr, no)
    }
  ')
  if [ -z "$ORDERED" ]; then
    IDENTITY_STATE="EMPTY"
    return 0
  fi
  CLASSIFIED=$(printf '%s\n' "$ORDERED" | "$_BIN/gstack-slug" --classify-checkpoints 2>/dev/null || true)
  if [ -z "$CLASSIFIED" ]; then
    IDENTITY_STATE="FAILED"
    UNVERIFIED_LINES=$(printf '%s\n' "$ORDERED" | sed 's/^/UNVERIFIED /')
    return 0
  fi

  FOREIGN_N=$(printf '%s\n' "$CLASSIFIED" | grep -c '^foreign' || true)
  MATCHED_ALL=$(printf '%s\n' "$CLASSIFIED" | awk -F '\t' \
    '$1 == "match" || $1 == "match-root" { print $2 }' | grep -v '^[[:space:]]*$' || true)
  if [ -n "$MATCHED_ALL" ]; then
    CLEARED_TS_MAP=$(printf '%s\n' "$MATCHED_ALL" | awk '
      $0 == "" { next }
      {
        f = $0; b = ""; clr = 0; seq = 0; fm = 0; ln = 0
        while ((getline line < f) > 0) {
          ln++; sub(/\r$/, "", line)
          if (ln == 1) { if (line == "---") { fm = 1; continue } else break }
          if (fm && line == "---") break
          if (fm && line ~ /^branch:/ && b == "") { sub(/^branch:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); b = line }
          else if (fm && line ~ /^carry_forward:/) { sub(/^carry_forward:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); if (tolower(line) == "cleared") clr = 1 }
          else if (fm && line ~ /^save_seq:/) { sub(/^save_seq:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); if (line ~ /^[0-9]+$/) seq = line + 0 }
        }
        close(f)
        if (clr && b != "") {
          n = split(f, segs, "/"); bn = segs[n]
          if (bn ~ /^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]/) {
            ts = substr(bn, 1, 15)
            k = b "\t" ts
            if (!(k in max_seq) || seq > max_seq[k]) max_seq[k] = seq
          }
        }
      }
      END {
        for (k in max_seq) print k "\t" max_seq[k]
      }
    ')
  fi
  VERIFIED_ALL=$(printf '%s\n' "$CLASSIFIED" | awk -F '\t' -v f="$FOREIGN_N" \
    '$1 == "match" || $1 == "match-root" || ($1 == "unstamped" && f == 0) { print $2 }' | grep -v '^[[:space:]]*$' || true)
  if [ -z "$VERIFIED_ALL" ]; then
    IDENTITY_STATE="NO_VERIFIED"
  fi
  local prefixed
  prefixed=$(printf '%s\n' "$CLASSIFIED" | awk -F '\t' -v f="$FOREIGN_N" \
    '$1 == "match-root" { print "ROOT_DIFFERS " $2 }
     $1 == "foreign" { print "FOREIGN " $2 }
     $1 == "unstamped" && f > 0 { print "UNVERIFIED " $2 }' || true)
  if [ -n "$prefixed" ]; then
    ROOT_DIFFERS_LINES=$(printf '%s\n' "$prefixed" | grep '^ROOT_DIFFERS ' || true)
    FOREIGN_LINES=$(printf '%s\n' "$prefixed" | grep '^FOREIGN ' || true)
    UNVERIFIED_LINES=$(printf '%s\n' "$prefixed" | grep '^UNVERIFIED ' || true)
  fi
}

_checkpoint_head() {
  tr -d '\r' < "$1" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && $0 == "---" { exit }
    fm && /^head:/ { sub(/^head:[ \t]*/, ""); sub(/[ \t]+$/, ""); print; exit }
  '
}

_checkpoint_carry_cleared() {
  local val
  val=$(tr -d '\r' < "$1" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && $0 == "---" { exit }
    fm && /^carry_forward:/ { sub(/^carry_forward:[ \t]*/, ""); sub(/[ \t]+$/, ""); print tolower($0); exit }
  ')
  [ "$val" = "cleared" ]
}

_checkpoint_save_seq() {
  local val
  val=$(tr -d '\r' < "$1" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && /^---[ \t]*$/ { exit }
    fm && /^save_seq:/ { sub(/^save_seq:[ \t]*/, ""); sub(/[ \t]+$/, ""); if ($0 ~ /^[0-9]+$/) print $0; exit }
  ')
  printf '%s' "${val:-0}"
}

_checkpoint_has_modified_files() {
  local val
  val=$(tr -d '\r' < "$1" 2>/dev/null | awk '
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && /^---[ \t]*$/ { exit }
    fm && in_mod {
      if ($0 ~ /^[ \t]*-[ \t]*[^ \t]/) { found = 1; exit }
      if ($0 !~ /^[ \t]*$/) in_mod = 0
    }
    fm && /^files_modified:/ {
      val = $0
      sub(/^files_modified:[ \t]*/, "", val)
      gsub(/^[ \t]+|[ \t]+$/, "", val)
      low = tolower(val)
      if (low == "") { in_mod = 1; next }
      if (low != "[]" && low != "none" && low != "null" && low != "~") { found = 1; exit }
    }
    END { print found + 0 }
  ')
  [ "${val:-0}" -eq 1 ]
}

# Extract substantive (non-stub, non-placeholder) lines from one structured section
# of a checkpoint file directly to out_file (or stdout if out_file is omitted).
# Supports 3+ char Markdown code fences and preserves blank lines inside fences.
# Kind is one of: decisions | reversals | promises.
_extract_checkpoint_section_to_file() {
  local file="$1" kind="$2" out_file="${3:-}"
  if [ -n "$out_file" ]; then
    tr -d '\r' < "$file" 2>/dev/null | awk -v kind="$kind" '
      function is_explicit_non_code_qualifier(q) {
        gsub(/^[ \t]+|[ \t]+$/, "", q)
        if (q == "") return 0
        if (q ~ /^(q&a|qa|inquiry|clarification|discussion|question|read[- ]only|non[- ]code|no code changes?|just checking|status check)( (only|turn|session))?$/) return 1
        if (q ~ /^(q&a|qa|inquiry|clarification|discussion)\/(q&a|qa|inquiry|clarification|discussion)( (only|turn|session))?$/) return 1
        return 0
      }
      function is_non_code_qualifier(q) {
        gsub(/^[ \t]+|[ \t]+$/, "", q)
        if (q == "") return 0
        if (is_explicit_non_code_qualifier(q)) return 1
        return (q ~ /^(no changes?|unchanged|same as (previous|before|prior)|this session|this turn|only)$/) ? 1 : 0
      }
      function is_explicit_non_code_stem(t) {
        return (t == "no code changes" || t == "no code changes made" || t == "no new code changes" ||
            t == "no code changes this session" || t == "no code changes in this session" ||
            t == "q&a only" || t == "qa only" || t == "q&a turn" || t == "qa turn" ||
            t == "inquiry only" || t == "inquiry turn" || t == "clarification only" ||
            t == "clarification turn" || t == "discussion only" || t == "discussion turn" ||
            t == "question only" || t == "read-only" || t == "read only" ||
            t == "read-only session" || t == "read only session" || t == "read-only turn" ||
            t == "read only turn" || t == "read-only q&a" || t == "read-only inquiry" ||
            t == "non-code session" || t == "non-code turn" || t == "non-code q&a")
      }
      function is_base_stub(t) {
        return (is_explicit_non_code_stem(t) ||
            t == "" || t == "-" || t == "--" || t == "—" || t == "–" ||
            t == "none" || t == "n/a" || t == "na" || t == "not applicable" ||
            t == "none applicable" || t == "none yet" || t == "none recorded" ||
            t == "none so far" || t == "none this session" || t == "none in this session" ||
            t == "nothing" || t == "nothing new" || t == "nothing changed" || t == "nothing recorded" ||
            t == "no changes" || t == "no changes made" || t == "no new changes" ||
            t == "no changes this session" || t == "no changes in this session" ||
            t == "no decisions" || t == "no new decisions" || t == "no active decisions" ||
            t == "no new active decisions" || t == "no decisions made" || t == "no new decisions made" ||
            t == "no decisions this session" || t == "no new decisions this session" ||
            t == "no reversals" || t == "no new reversals" || t == "no reversals made" ||
            t == "no reversals recorded" || t == "no reversals this session" || t == "no new reversals this session" ||
            t == "no promises" || t == "no open promises" || t == "no new promises" ||
            t == "no new open promises" || t == "no next step" || t == "no next steps" ||
            t == "no new next step" || t == "no new next steps" || t == "no remaining work" ||
            t == "no open work" || t == "no pending promises" || t == "no pending work" ||
            t == "same as previous" || t == "same as before" || t == "same as prior" ||
            t == "unchanged" || t == "carried forward" || t == "see previous" ||
            t == "see previous checkpoint" || t == "tbd")
      }
      function strip_stub_wrap(s,    t) {
        t = tolower(s)
        gsub(/^[ \t]+|[ \t]+$/, "", t)
        if (t == "") return ""
        sub(/^(-|\*|•|[0-9]+[.)])[ \t]*/, "", t)
        gsub(/^[ \t*_`]+/, "", t)
        gsub(/[ \t*_`.!]+$/, "", t)
        while ((substr(t, 1, 1) == "(" && substr(t, length(t), 1) == ")" && index(substr(t, 2, length(t) - 2), "(") == 0) ||
               (substr(t, 1, 1) == "[" && substr(t, length(t), 1) == "]" && index(substr(t, 2, length(t) - 2), "[") == 0)) {
          t = substr(t, 2, length(t) - 2)
          gsub(/^[ \t*_`]+/, "", t)
          gsub(/[ \t*_`.!]+$/, "", t)
        }
        return t
      }
      function classify_stub(s,    t, head, tail) {
        # Returns: 2 = explicit non-code stub, 1 = generic stub, 0 = substantive
        t = strip_stub_wrap(s)
        if (is_explicit_non_code_stem(t)) return 2
        if (is_base_stub(t)) return 1
        if (match(t, /[ \t]*\([^()]*\)$/)) {
          head = substr(t, 1, RSTART - 1)
          tail = substr(t, RSTART, RLENGTH)
          gsub(/^[ \t]*\(/, "", tail); gsub(/\)[ \t]*$/, "", tail)
          gsub(/[ \t]+$/, "", head)
          if (is_base_stub(head) && is_non_code_qualifier(tail)) {
            return (is_explicit_non_code_stem(head) || is_explicit_non_code_qualifier(tail)) ? 2 : 1
          }
        }
        if (match(t, /([ \t]*(—|–|--|;|,|:)[ \t]*|[ \t]+-[ \t]+)/)) {
          head = substr(t, 1, RSTART - 1)
          tail = substr(t, RSTART + RLENGTH)
          gsub(/[ \t]+$/, "", head)
          if (is_base_stub(head) && is_non_code_qualifier(tail)) {
            return (is_explicit_non_code_stem(head) || is_explicit_non_code_qualifier(tail)) ? 2 : 1
          }
        }
        return 0
      }
      function leading_indent(s,    i, c, n) {
        n = 0
        for (i = 1; i <= length(s); i++) {
          c = substr(s, i, 1)
          if (c == " ") n++
          else if (c == "\t") n += 4
          else break
        }
        return n
      }
      function is_list_marker(s) {
        return (s ~ /^ ? ? ?(-|\*|•|[0-9]+[.)])[ \t]+/)
      }
      function is_stub_line(s) {
        return (classify_stub(s) > 0) ? 1 : 0
      }
      function match_heading(line, low) {
        if (line !~ /^###?[ \t]+/) return ""
        low = tolower(line)
        sub(/^###?[ \t]+/, "", low)
        gsub(/[ \t]+$/, "", low)
        if (low == "active decisions" || low == "decisions made") return "decisions"
        if (low == "reversals / do-not-repeat" || low == "reversals/do-not-repeat" || low == "reversals") return "reversals"
        if (low == "open promises / next step" || low == "open promises / next steps" ||
            low == "open promises/next step" || low == "open promises/next steps" ||
            low == "open promises" || low == "next step" || low == "next steps" ||
            low == "remaining work") return "promises"
        return "other"
      }
      function step_fence(line,    rest, ch, len) {
        if (!fence_ch) {
          if (match(line, /^ ? ? ?(```+|~~~+)/)) {
            rest = substr(line, RSTART, RLENGTH)
            sub(/^ +/, "", rest)
            ch = substr(rest, 1, 1)
            len = length(rest)
            if (ch == "`" && index(substr(line, RSTART + RLENGTH), "`") > 0) return 0
            fence_ch = ch
            fence_len = len
            return 1
          }
          return 0
        } else {
          if (match(line, /^ ? ? ?(```+|~~~+)[ \t]*$/)) {
            rest = substr(line, RSTART, RLENGTH)
            gsub(/^[ \t]+|[ \t]+$/, "", rest)
            if (substr(rest, 1, 1) == fence_ch && length(rest) >= fence_len) {
              fence_ch = ""
              fence_len = 0
              return 1
            }
          }
          return 0
        }
      }
      NR == 1 && $0 == "---" { fm = 1; next }
      fm && /^---[ \t]*$/ { fm = 0; next }
      fm { next }
      {
        was_fenced = (fence_ch != "")
        toggled = step_fence($0)
        if (toggled || was_fenced) {
          if (in_sec) {
            has_real = 1
            buf[++n] = $0
            in_fence_line[n] = 1
          }
          next
        }
      }
      /^###?[ \t]+/ {
        k = match_heading($0)
        if (k == kind || (kind == "explicit-non-code" && k == "decisions")) {
          in_sec = 1; sec_base_ind = -1; cur_parent_real = 0; sec_has_item = 0
          next
        }
        if (in_sec) { in_sec = 0; sec_base_ind = -1; cur_parent_real = 0; sec_has_item = 0 }
        next
      }
      in_sec {
        if ($0 ~ /^[ \t]*$/) next
        ind = leading_indent($0)
        is_m = is_list_marker($0)
        if (sec_base_ind < 0) sec_base_ind = is_m ? ind : 0
        is_child = (sec_has_item && !((is_m && ind <= sec_base_ind) || (!is_m && ind == 0 && sec_base_ind == 0)))
        buf[++n] = $0
        in_fence_line[n] = 0
        if (is_child && cur_parent_real) {
          has_real = 1
          keep_line[n] = 1
        } else {
          cls = classify_stub($0)
          if (!is_child) {
            if (is_m && ind < sec_base_ind) sec_base_ind = ind
            cur_parent_real = (cls == 0) ? 1 : 0
            sec_has_item = 1
          }
          if (cls == 0) {
            has_real = 1
            keep_line[n] = 1
          } else {
            if (cls == 2) has_explicit_nc = 1
            keep_line[n] = 0
          }
        }
      }
      END {
        if (kind == "explicit-non-code") {
          if (has_explicit_nc && !has_real) print "1"
        } else if (has_real) {
          for (i = 1; i <= n; i++) {
            if (in_fence_line[i] || keep_line[i]) print buf[i]
          }
        }
      }
    ' > "$out_file"
  else
    local tmp
    tmp=$(mktemp "${TMPDIR:-/tmp}/.ckpt-sec-XXXXXX") || return 2
    if ! _extract_checkpoint_section_to_file "$file" "$kind" "$tmp"; then
      rm -f "$tmp"
      return 2
    fi
    cat "$tmp"
    rm -f "$tmp"
  fi
}

_extract_checkpoint_section() {
  _extract_checkpoint_section_to_file "$1" "$2"
}

# Returns 0 if file contains a heading for kind (decisions | reversals | promises | any) outside fences.
_has_section_heading() {
  local file="$1" kind="$2"
  local found
  found=$(tr -d '\r' < "$file" 2>/dev/null | awk -v kind="$kind" '
    function match_heading(line, low) {
      if (line !~ /^###?[ \t]+/) return ""
      low = tolower(line)
      sub(/^###?[ \t]+/, "", low)
      gsub(/[ \t]+$/, "", low)
      if (low == "active decisions" || low == "decisions made") return "decisions"
      if (low == "reversals / do-not-repeat" || low == "reversals/do-not-repeat" || low == "reversals") return "reversals"
      if (low == "open promises / next step" || low == "open promises / next steps" ||
          low == "open promises/next step" || low == "open promises/next steps" ||
          low == "open promises" || low == "next step" || low == "next steps" ||
          low == "remaining work") return "promises"
      return "other"
    }
    function step_fence(line,    rest, ch, len) {
      if (!fence_ch) {
        if (match(line, /^ ? ? ?(```+|~~~+)/)) {
          rest = substr(line, RSTART, RLENGTH)
          sub(/^ +/, "", rest)
          ch = substr(rest, 1, 1)
          len = length(rest)
          if (ch == "`" && index(substr(line, RSTART + RLENGTH), "`") > 0) return 0
          fence_ch = ch; fence_len = len; return 1
        }
        return 0
      } else {
        if (match(line, /^ ? ? ?(```+|~~~+)[ \t]*$/)) {
          rest = substr(line, RSTART, RLENGTH)
          gsub(/^[ \t]+|[ \t]+$/, "", rest)
          if (substr(rest, 1, 1) == fence_ch && length(rest) >= fence_len) {
            fence_ch = ""; fence_len = 0; return 1
          }
        }
        return 0
      }
    }
    NR == 1 && $0 == "---" { fm = 1; next }
    fm && /^---[ \t]*$/ { fm = 0; next }
    fm { next }
    {
      was_fenced = (fence_ch != "")
      if (step_fence($0) || was_fenced) next
    }
    /^###?[ \t]+/ {
      k = match_heading($0)
      if ((kind == "any" && (k == "decisions" || k == "reversals" || k == "promises")) || k == kind) {
        found = 1; exit
      }
    }
    END { print found + 0 }
  ')
  [ "${found:-0}" -eq 1 ]
}

# Returns 0 if file's Active Decisions section contains only non-substantive stub lines
# AND explicitly states a non-code / Q&A stub phrase (e.g. "No code changes", "Q&A only",
# "None (no code changes)"). Bare "None." / "N/A" alone returns 1 so explicit post-commit
# or dirty-checkout clearing is preserved.
_has_explicit_non_code_stub() {
  [ "$(_extract_checkpoint_section "$1" explicit-non-code)" = "1" ]
}

# File-backed whole-item deduplicating merge (avoids env-var E2BIG, preserves 0-3 space
# indented top-level bullets, keeps nested child constraints under repeated parents,
# tracks 3+ char code fences, and never renumbers fenced code lines).
_dedup_merge_files() {
  local new_file="$1" prev_file="$2" numbered="${3:-0}" out_file="$4" only_prev="${5:-0}"
  awk -v numbered="$numbered" -v prev_f="$prev_file" -v only_prev="$only_prev" '
    function leading_indent(s,    i, c, n) {
      n = 0
      for (i = 1; i <= length(s); i++) {
        c = substr(s, i, 1)
        if (c == " ") n++
        else if (c == "\t") n += 4
        else break
      }
      return n
    }
    function is_list_marker(s) {
      return (s ~ /^ ? ? ?(-|\*|•|[0-9]+[.)])[ \t]+/)
    }
    function norm_first(s, k) {
      k = s
      gsub(/^[ \t]+|[ \t]+$/, "", k)
      sub(/^(-|\*|•|[0-9]+[.)])[ \t]+/, "", k)
      sub(/[.]+$/, "", k)
      return k
    }
    function norm_child(s, k) {
      k = s
      gsub(/[ \t]+$/, "", k)
      return k
    }
    function step_fence(line,    rest, ch, len) {
      if (!f_ch) {
        if (match(line, /^ ? ? ?(```+|~~~+)/)) {
          rest = substr(line, RSTART, RLENGTH)
          sub(/^ +/, "", rest)
          ch = substr(rest, 1, 1)
          len = length(rest)
          if (ch == "`" && index(substr(line, RSTART + RLENGTH), "`") > 0) return 0
          f_ch = ch; f_len = len; return 1
        }
        return 0
      } else {
        if (match(line, /^ ? ? ?(```+|~~~+)[ \t]*$/)) {
          rest = substr(line, RSTART, RLENGTH)
          gsub(/^[ \t]+|[ \t]+$/, "", rest)
          if (substr(rest, 1, 1) == f_ch && length(rest) >= f_len) {
            f_ch = ""; f_len = 0; return 1
          }
        }
        return 0
      }
    }
    function flush_item(    key, j, first_line, out_first) {
      if (cur_n == 0) return
      key = norm_first(cur_lines[1])
      for (j = 2; j <= cur_n; j++) {
        key = key "\n" norm_child(cur_lines[j])
      }
      if (only_prev && !is_prev) {
        if (key != "") seen[key] = 1
        cur_n = 0
        return
      }
      if (is_prev && key != "" && (key in seen)) {
        cur_n = 0
        return
      }
      if (key != "") seen[key] = 1
      first_line = cur_lines[1]
      if (numbered == 1 && !cur_first_fence) {
        out_first = first_line
        sub(/^ ? ? ?(-|\*|•|[0-9]+[.)])[ \t]+/, "", out_first)
        idx++
        print idx ". " out_first
      } else {
        print first_line
      }
      for (j = 2; j <= cur_n; j++) {
        print cur_lines[j]
      }
      cur_n = 0
    }
    FILENAME != cur_file {
      flush_item()
      cur_file = FILENAME
      is_prev = (FILENAME == prev_f) ? 1 : 0
      f_ch = ""; f_len = 0
      base_indent = -1
    }
    {
      line = $0
      was_fenced = (f_ch != "")
      toggled = step_fence(line)
      if (was_fenced || toggled) {
        if (cur_n == 0) {
          cur_n = 1
          cur_lines[1] = line
          cur_first_fence = 1
        } else {
          cur_lines[++cur_n] = line
        }
        next
      }
      if (line ~ /^[ \t]*$/) next
      ind = leading_indent(line)
      is_marker = is_list_marker(line)
      if (cur_n == 0) {
        base_indent = is_marker ? ind : 0
        cur_n = 1
        cur_lines[1] = line
        cur_first_fence = 0
        next
      }
      if ((is_marker && ind <= base_indent) || (!is_marker && ind == 0 && base_indent == 0)) {
        flush_item()
        if (is_marker && ind < base_indent) base_indent = ind
        cur_n = 1
        cur_lines[1] = line
        cur_first_fence = 0
      } else {
        cur_lines[++cur_n] = line
      }
    }
    END {
      flush_item()
    }
  ' "$new_file" "$prev_file" > "$out_file"
}

# Output ONLY items from extra_file whose normalized whole-item key is absent from base_file.
_diff_only_new_items() {
  local base_file="$1" extra_file="$2" numbered="${3:-0}" out_file="$4"
  if [ ! -s "$extra_file" ]; then
    : > "$out_file"
    return 0
  fi
  _dedup_merge_files "$base_file" "$extra_file" "$numbered" "$out_file" 1
}

# File-backed reversal comparison. Returns 0 if new_file introduces any reversal item
# not present in prev_file, 1 if not, 2 on error.
_has_new_reversal_files() {
  local new_file="$1" prev_file="$2"
  [ -s "$new_file" ] || return 1
  [ -s "$prev_file" ] || return 0
  local has_new
  has_new=$(awk -v new_f="$new_file" '
    function leading_indent(s,    i, c, n) {
      n = 0
      for (i = 1; i <= length(s); i++) {
        c = substr(s, i, 1)
        if (c == " ") n++
        else if (c == "\t") n += 4
        else break
      }
      return n
    }
    function is_list_marker(s) {
      return (s ~ /^ ? ? ?(-|\*|•|[0-9]+[.)])[ \t]+/)
    }
    function norm_first(s, k) {
      k = s
      gsub(/^[ \t]+|[ \t]+$/, "", k)
      sub(/^(-|\*|•|[0-9]+[.)])[ \t]+/, "", k)
      sub(/[.]+$/, "", k)
      return k
    }
    function norm_child(s, k) {
      k = s
      gsub(/[ \t]+$/, "", k)
      return k
    }
    function step_fence(line,    rest, ch, len) {
      if (!f_ch) {
        if (match(line, /^ ? ? ?(```+|~~~+)/)) {
          rest = substr(line, RSTART, RLENGTH)
          sub(/^ +/, "", rest)
          ch = substr(rest, 1, 1)
          len = length(rest)
          if (ch == "`" && index(substr(line, RSTART + RLENGTH), "`") > 0) return 0
          f_ch = ch; f_len = len; return 1
        }
        return 0
      } else {
        if (match(line, /^ ? ? ?(```+|~~~+)[ \t]*$/)) {
          rest = substr(line, RSTART, RLENGTH)
          gsub(/^[ \t]+|[ \t]+$/, "", rest)
          if (substr(rest, 1, 1) == f_ch && length(rest) >= f_len) {
            f_ch = ""; f_len = 0; return 1
          }
        }
        return 0
      }
    }
    function flush_item(    key, j) {
      if (cur_n == 0) return
      key = norm_first(cur_lines[1])
      for (j = 2; j <= cur_n; j++) key = key "\n" norm_child(cur_lines[j])
      if (key != "") {
        if (is_new) new_items[key] = 1
        else prev_items[key] = 1
      }
      cur_n = 0
    }
    FNR == 1 {
      flush_item()
      is_new = (FILENAME == new_f) ? 1 : 0
      f_ch = ""; f_len = 0
      base_indent = -1
    }
    {
      line = $0
      was_fenced = (f_ch != "")
      toggled = step_fence(line)
      if (was_fenced || toggled) {
        cur_lines[++cur_n] = line
        next
      }
      if (line ~ /^[ \t]*$/) next
      ind = leading_indent(line)
      is_marker = is_list_marker(line)
      if (cur_n == 0) {
        base_indent = is_marker ? ind : 0
        cur_n = 1; cur_lines[1] = line; next
      }
      if ((is_marker && ind <= base_indent) || (!is_marker && ind == 0 && base_indent == 0)) {
        flush_item()
        if (is_marker && ind < base_indent) base_indent = ind
        cur_n = 1; cur_lines[1] = line
      } else {
        cur_lines[++cur_n] = line
      }
    }
    END {
      flush_item()
      found = 0
      for (k in new_items) {
        if (!(k in prev_items)) { found = 1; break }
      }
      print found
    }
  ' "$prev_file" "$new_file") || return 2
  [ "${has_new:-0}" -eq 1 ]
}

# Filter prev_file reversals, dropping prior opposite/re-reversed lines contradicted by
# new reversals in nrev_file (and active decisions in ndec_file) while preserving all
# unrelated prior reversals and multi-line indented children verbatim.
_prune_superseded_reversals() {
  local nrev_file="$1" ndec_file="$2" prev_file="$3" out_file="$4"
  awk -v nrev_f="$nrev_file" -v ndec_f="$ndec_file" '
    function leading_indent(s,    i, c, n) {
      n = 0
      for (i = 1; i <= length(s); i++) {
        c = substr(s, i, 1)
        if (c == " ") n++
        else if (c == "\t") n += 4
        else break
      }
      return n
    }
    function is_list_marker(s) {
      return (s ~ /^ ? ? ?(-|\*|•|[0-9]+[.)])[ \t]+/)
    }
    function step_fence(line,    rest, ch, len) {
      if (!f_ch) {
        if (match(line, /^ ? ? ?(```+|~~~+)/)) {
          rest = substr(line, RSTART, RLENGTH)
          sub(/^ +/, "", rest)
          ch = substr(rest, 1, 1); len = length(rest)
          if (ch == "`" && index(substr(line, RSTART + RLENGTH), "`") > 0) return 0
          f_ch = ch; f_len = len; return 1
        }
        return 0
      } else {
        if (match(line, /^ ? ? ?(```+|~~~+)[ \t]*$/)) {
          rest = substr(line, RSTART, RLENGTH)
          gsub(/^[ \t]+|[ \t]+$/, "", rest)
          if (substr(rest, 1, 1) == f_ch && length(rest) >= f_len) {
            f_ch = ""; f_len = 0; return 1
          }
        }
        return 0
      }
    }
    function norm_term(s,    k) {
      k = tolower(s)
      gsub(/[`*_~]/, "", k)
      gsub(/[^a-z0-9]+/, " ", k)
      gsub(/^ +| +$/, "", k)
      return k
    }
    function core_term(s,    k) {
      k = norm_term(s)
      sub(/^(switch back to|revert back to|go back to|move back to|back to|switch to|revert to|move to|keep using|use|using|keep|keeping|adopt|adopting|re enable|reenable|restore|restoring) +/, "", k)
      sub(/^(the|a|an) +/, "", k)
      return k
    }
    function terms_match_exact(a, b,    ca, cb) {
      ca = core_term(a); cb = core_term(b)
      return (ca != "" && cb != "" && ca == cb) ? 1 : 0
    }
    function terms_match_loose(a, b,    ca, cb, pa, pb) {
      ca = core_term(a); cb = core_term(b)
      if (ca == "" || cb == "") return 0
      if (ca == cb) return 1
      pa = " " ca " "; pb = " " cb " "
      if (length(ca) >= 3 && index(pb, pa) > 0) return 1
      if (length(cb) >= 3 && index(pa, pb) > 0) return 1
      return 0
    }
    function parse_reversal_pair(line,    p1, rest, p2, after, rhs) {
      pair_old = ""; pair_new = ""
      p1 = index(line, "~~")
      if (p1 == 0) return 0
      rest = substr(line, p1 + 2)
      p2 = index(rest, "~~")
      if (p2 == 0) return 0
      pair_old = substr(rest, 1, p2 - 1)
      after = substr(rest, p2 + 2)
      if (!match(after, /(--?>|=>|→)/)) return 0
      rhs = substr(after, RSTART + RLENGTH)
      gsub(/^[ \t]+|[ \t]+$/, "", rhs)
      if (match(rhs, /[ \t]*\([^()]*\)[ \t.;,]*$/) && RSTART > 1) {
        rhs = substr(rhs, 1, RSTART - 1)
        gsub(/[ \t]+$/, "", rhs)
      }
      pair_new = rhs
      return (pair_old != "" && pair_new != "") ? 1 : 0
    }
    function is_negative_decision(s,    k) {
      k = norm_term(s)
      return (k ~ /^(never|do not|don t|dont|avoid|no|not|stop|drop|forbid|ban) /) ? 1 : 0
    }
    function is_contradicted(p_old, p_new,    i, d) {
      for (i = 1; i <= n_pairs; i++) {
        if (terms_match_loose(p_old, new_new[i]) && terms_match_loose(p_new, new_old[i])) return 1
        for (d = 1; d <= n_decs; d++) {
          if (!is_negative_decision(decs[d]) && terms_match_exact(p_old, decs[d]) && terms_match_loose(p_new, new_old[i])) return 1
        }
      }
      return 0
    }
    function flush_item(    j, fl) {
      if (cur_n == 0) return
      fl = cur_lines[1]
      if (mode == "nrev") {
        if (parse_reversal_pair(fl)) {
          n_pairs++
          new_old[n_pairs] = pair_old
          new_new[n_pairs] = pair_new
        }
      } else if (mode == "ndec") {
        sub(/^ ? ? ?(-|\*|•|[0-9]+[.)])[ \t]+/, "", fl)
        if (fl != "") decs[++n_decs] = fl
      } else {
        if (!parse_reversal_pair(fl) || !is_contradicted(pair_old, pair_new)) {
          for (j = 1; j <= cur_n; j++) print cur_lines[j]
        }
      }
      cur_n = 0
    }
    FILENAME != cur_file {
      flush_item()
      cur_file = FILENAME
      if (cur_file == nrev_f) mode = "nrev"
      else if (cur_file == ndec_f) mode = "ndec"
      else mode = "prev"
      f_ch = ""; f_len = 0
      base_indent = -1
    }
    {
      line = $0
      was_fenced = (f_ch != "")
      toggled = step_fence(line)
      if (was_fenced || toggled) {
        cur_lines[++cur_n] = line
        next
      }
      if (line ~ /^[ \t]*$/) next
      ind = leading_indent(line)
      is_marker = is_list_marker(line)
      if (cur_n == 0) {
        base_indent = is_marker ? ind : 0
        cur_n = 1; cur_lines[1] = line; next
      }
      if ((is_marker && ind <= base_indent) || (!is_marker && ind == 0 && base_indent == 0)) {
        flush_item()
        if (is_marker && ind < base_indent) base_indent = ind
        cur_n = 1; cur_lines[1] = line
      } else {
        cur_lines[++cur_n] = line
      }
    }
    END {
      flush_item()
    }
  ' "$nrev_file" "$ndec_file" "$prev_file" > "$out_file"
}

# Check whether any verified same-branch checkpoint at ts has carry_forward: cleared
# with save_seq >= min_seq (defaults to 0). Uses the prebuilt CLEARED_TS_MAP lookup (zero forks).
_timestamp_has_cleared() {
  local ts="$1" br="$2" min_seq="${3:-0}" cb cts cseq
  [ -n "$ts" ] && [ -n "${CLEARED_TS_MAP:-}" ] || return 1
  while IFS="$_TAB" read -r cb cts cseq; do
    [ -n "$cb" ] || continue
    if [ "$cb" = "$br" ] && [ "$cts" = "$ts" ] && [ "${cseq:-0}" -ge "$min_seq" ] 2>/dev/null; then
      return 0
    fi
  done <<EOF
$CLEARED_TS_MAP
EOF
  return 1
}

# Merge still-open Active Decisions, Reversals / Do-Not-Repeat, and Open Promises / Next Step
# from prev_file into body_in -> body_out. Sets CARRIED_PROMISES and MIXED_PROMISES.
# Returns 0 if carried forward, 1 if nothing to carry, 2 on error.
_apply_carry_forward() {
  local body_in="$1" prev_file="$2" is_non_code="$3" explicit_carry="$4" body_out="$5"
  local cf_dir carry_dec=0 carry_rev=0 carry_prom=0 has_new_rev=0 rc=0
  local explicit_none_dec=0 explicit_none_rev=0 explicit_none_prom=0
  local f_pdec f_prev f_pprom f_ndec f_nrev f_nprom f_fdec="" f_frev="" f_fprom="" f_mdec f_mrev f_mprom
  CARRIED_PROMISES=0
  MIXED_PROMISES=0

  cf_dir=$(mktemp -d "${CHECKPOINT_DIR}/.cf-XXXXXX" 2>/dev/null) || return 2
  f_pdec="$cf_dir/pdec"; f_prev="$cf_dir/prev"; f_pprom="$cf_dir/pprom"
  f_ndec="$cf_dir/ndec"; f_nrev="$cf_dir/nrev"; f_nprom="$cf_dir/nprom"
  f_mdec="$cf_dir/mdec"; f_mrev="$cf_dir/mrev"; f_mprom="$cf_dir/mprom"

  if ! _extract_checkpoint_section_to_file "$prev_file" decisions "$f_pdec" \
    || ! _extract_checkpoint_section_to_file "$prev_file" reversals "$f_prev" \
    || ! _extract_checkpoint_section_to_file "$prev_file" promises "$f_pprom" \
    || ! _extract_checkpoint_section_to_file "$body_in" decisions "$f_ndec" \
    || ! _extract_checkpoint_section_to_file "$body_in" reversals "$f_nrev" \
    || ! _extract_checkpoint_section_to_file "$body_in" promises "$f_nprom"; then
    rm -rf "$cf_dir"
    return 2
  fi

  if [ ! -s "$f_pdec" ] && [ ! -s "$f_prev" ] && [ ! -s "$f_pprom" ]; then
    rm -rf "$cf_dir"
    return 1
  fi

  rc=0
  _has_new_reversal_files "$f_nrev" "$f_prev" || rc=$?
  if [ "$rc" -ge 2 ]; then
    rm -rf "$cf_dir"
    return 2
  elif [ "$rc" -eq 0 ]; then
    has_new_rev=1
  fi

  if [ ! -s "$f_ndec" ] && _has_section_heading "$body_in" decisions; then explicit_none_dec=1; fi
  if [ ! -s "$f_nrev" ] && _has_section_heading "$body_in" reversals; then explicit_none_rev=1; fi
  if [ ! -s "$f_nprom" ] && _has_section_heading "$body_in" promises; then explicit_none_prom=1; fi

  if [ -s "$f_pdec" ]; then
    if [ ! -s "$f_ndec" ]; then
      if [ "$explicit_carry" -eq 1 ] \
        || { [ "$has_new_rev" -eq 0 ] && { [ "$is_non_code" -eq 1 ] || [ "$explicit_none_dec" -eq 0 ]; }; }; then
        f_fdec="$f_pdec"
        carry_dec=1
      fi
    elif [ "$explicit_carry" -eq 1 ] || { [ "$is_non_code" -eq 1 ] && [ "$has_new_rev" -eq 0 ]; }; then
      if ! _dedup_merge_files "$f_ndec" "$f_pdec" 0 "$f_mdec"; then
        rm -rf "$cf_dir"
        return 2
      fi
      if ! cmp -s "$f_mdec" "$f_ndec"; then
        f_fdec="$f_mdec"
        carry_dec=1
      fi
    fi
  fi

  if [ -s "$f_prev" ]; then
    if [ ! -s "$f_nrev" ]; then
      if [ "$explicit_carry" -eq 1 ] || [ "$is_non_code" -eq 1 ] || [ "$explicit_none_rev" -eq 0 ]; then
        f_frev="$f_prev"
        carry_rev=1
      fi
    else
      local f_prev_use="$f_prev"
      if [ "$has_new_rev" -eq 1 ]; then
        f_prev_use="$cf_dir/prev_pruned"
        if ! _prune_superseded_reversals "$f_nrev" "$f_ndec" "$f_prev" "$f_prev_use"; then
          rm -rf "$cf_dir"
          return 2
        fi
      fi
      if [ -s "$f_prev_use" ]; then
        if ! _dedup_merge_files "$f_nrev" "$f_prev_use" 0 "$f_mrev"; then
          rm -rf "$cf_dir"
          return 2
        fi
        if ! cmp -s "$f_mrev" "$f_nrev"; then
          f_frev="$f_mrev"
          carry_rev=1
        fi
      fi
    fi
  fi

  if [ -s "$f_pprom" ]; then
    if [ ! -s "$f_nprom" ]; then
      if [ "$explicit_carry" -eq 1 ] \
        || { [ "$has_new_rev" -eq 0 ] && { [ "$is_non_code" -eq 1 ] || [ "$explicit_none_prom" -eq 0 ]; }; }; then
        f_fprom="$f_pprom"
        carry_prom=1
      fi
    elif [ "$explicit_carry" -eq 1 ] || { [ "$is_non_code" -eq 1 ] && [ "$has_new_rev" -eq 0 ]; }; then
      if ! _diff_only_new_items "$f_nprom" "$f_pprom" 0 "$cf_dir/diff_prom"; then
        rm -rf "$cf_dir"
        return 2
      fi
      if [ -s "$cf_dir/diff_prom" ]; then
        if ! _dedup_merge_files "$f_nprom" "$f_pprom" 1 "$f_mprom"; then
          rm -rf "$cf_dir"
          return 2
        fi
        if ! cmp -s "$f_mprom" "$f_nprom"; then
          f_fprom="$f_mprom"
          carry_prom=1
          MIXED_PROMISES=1
        fi
      fi
    fi
  fi

  if [ "$carry_dec" -eq 0 ] && [ "$carry_rev" -eq 0 ] && [ "$carry_prom" -eq 0 ]; then
    rm -rf "$cf_dir"
    return 1
  fi
  CARRIED_PROMISES="$carry_prom"

  if ! awk -v cdec="$carry_dec" -v crev="$carry_rev" -v cprom="$carry_prom" \
    -v fdec="$f_fdec" -v frev="$f_frev" -v fprom="$f_fprom" '
      function emit_file(p,    fl) {
        while ((getline fl < p) > 0) print fl
        close(p)
      }
      function heading_kind(line, low) {
        if (line !~ /^###?[ \t]+/) return ""
        low = tolower(line)
        sub(/^###?[ \t]+/, "", low)
        gsub(/[ \t]+$/, "", low)
        if (low == "active decisions" || low == "decisions made") return "decisions"
        if (low == "reversals / do-not-repeat" || low == "reversals/do-not-repeat" || low == "reversals") return "reversals"
        if (low == "open promises / next step" || low == "open promises / next steps" ||
            low == "open promises/next step" || low == "open promises/next steps" ||
            low == "open promises" || low == "next step" || low == "next steps" ||
            low == "remaining work") return "promises"
        if (low == "workspace") return "workspace"
        return "other"
      }
      function step_fence(line,    rest, ch, len) {
        if (!fence_ch) {
          if (match(line, /^ ? ? ?(```+|~~~+)/)) {
            rest = substr(line, RSTART, RLENGTH)
            sub(/^ +/, "", rest)
            ch = substr(rest, 1, 1)
            len = length(rest)
            if (ch == "`" && index(substr(line, RSTART + RLENGTH), "`") > 0) return 0
            fence_ch = ch; fence_len = len; return 1
          }
          return 0
        } else {
          if (match(line, /^ ? ? ?(```+|~~~+)[ \t]*$/)) {
            rest = substr(line, RSTART, RLENGTH)
            gsub(/^[ \t]+|[ \t]+$/, "", rest)
            if (substr(rest, 1, 1) == fence_ch && length(rest) >= fence_len) {
              fence_ch = ""; fence_len = 0; return 1
            }
          }
          return 0
        }
      }
      function emit_missing(did) {
        did = 0
        if (cdec && !w_dec) {
          if (printed_any) print ""
          print "### Active Decisions"
          emit_file(fdec)
          w_dec = 1; printed_any = 1; did = 1
        }
        if (crev && !w_rev) {
          if (printed_any) print ""
          print "### Reversals / Do-Not-Repeat"
          emit_file(frev)
          w_rev = 1; printed_any = 1; did = 1
        }
        if (cprom && !w_prom) {
          if (printed_any) print ""
          print "### Open Promises / Next Step"
          emit_file(fprom)
          w_prom = 1; printed_any = 1; did = 1
        }
        return did
      }
      NR == 1 && $0 == "---" { fm = 1; print; printed_any = 1; next }
      fm && /^---[ \t]*$/ { fm = 0; print; printed_any = 1; next }
      fm { print; printed_any = 1; next }
      {
        was_fenced = (fence_ch != "")
        toggled = step_fence($0)
        if (toggled || was_fenced) {
          if (!skip) { print; printed_any = 1 }
          next
        }
      }
      /^###?[ \t]+/ {
        k = heading_kind($0)
        was_skip = skip
        if (skip) {
          skip = 0
        }
        if (k == "workspace") {
          emitted = emit_missing()
          if (was_skip || emitted) print ""
          print
          printed_any = 1
          next
        }
        if (k == "decisions" && cdec) {
          if (!w_dec) {
            if (was_skip) print ""
            print
            emit_file(fdec)
            w_dec = 1; printed_any = 1
          }
          skip = 1
          next
        }
        if (k == "reversals" && crev) {
          if (!w_rev) {
            if (was_skip) print ""
            print
            emit_file(frev)
            w_rev = 1; printed_any = 1
          }
          skip = 1
          next
        }
        if (k == "promises" && cprom) {
          if (!w_prom) {
            if (was_skip) print ""
            print
            emit_file(fprom)
            w_prom = 1; printed_any = 1
          }
          skip = 1
          next
        }
        if (was_skip) print ""
        print
        printed_any = 1
        next
      }
      !skip { print; printed_any = 1 }
      END {
        emit_missing()
      }
    ' "$body_in" > "$body_out"; then
    rm -rf "$cf_dir"
    return 2
  fi
  rm -rf "$cf_dir"
  return 0
}

_emit_prior_open_context() {
  local file="$1" id_tag="$2"
  case "$id_tag" in
    OK|ROOT_DIFFERS) ;;
    *) return 0 ;;
  esac
  # Fast bailout when there is at most one positively matched checkpoint (zero forks).
  case "${MATCHED_ALL:-}" in
    *$'\n'*) ;;
    *) return 0 ;;
  esac
  # Single-fork fast check: read selected file frontmatter (carry_forward + branch) and
  # bail immediately unless another matched checkpoint on the same branch has structured sections.
  local has_prior_sec
  has_prior_sec=$(printf '%s\n' "$MATCHED_ALL" | GSTACK_SEL_F="$file" awk '
    BEGIN {
      sel = ENVIRON["GSTACK_SEL_F"]; cur = ""; cleared = 0; found = 0
      fm = 0; ln = 0
      while ((getline line < sel) > 0) {
        ln++; sub(/\r$/, "", line)
        if (ln == 1) { if (line == "---") { fm = 1; continue } else break }
        if (fm && line == "---") break
        if (fm && line ~ /^branch:/ && cur == "") {
          sub(/^branch:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); cur = line
        } else if (fm && line ~ /^carry_forward:/) {
          sub(/^carry_forward:[ \t]*/, "", line); sub(/[ \t]+$/, "", line)
          if (tolower(line) == "cleared") cleared = 1
        }
      }
      close(sel)
      if (cleared || cur == "" || cur == "unknown" || cur == "HEAD") exit
    }
    $0 == "" || $0 == sel { next }
    {
      f = $0; b = ""; fm = 0; ln = 0; has_sec = 0
      while ((getline line < f) > 0) {
        ln++; sub(/\r$/, "", line)
        if (ln == 1 && line == "---") { fm = 1; continue }
        if (fm && line == "---") { fm = 0; continue }
        if (fm) {
          if (line ~ /^branch:/ && b == "") {
            sub(/^branch:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); b = line
          }
          continue
        }
        if (b != cur) break
        low = tolower(line)
        if (low ~ /^###?[ \t]+(active decisions|decisions made|reversals|open promises|next step|remaining work)/) {
          has_sec = 1; break
        }
      }
      close(f)
      if (b == cur && has_sec) { found = 1; exit }
    }
    END { print found }
  ')
  [ "${has_prior_sec:-0}" -eq 1 ] || return 0

  local sel_branch sel_ts sel_seq sel_head sel_dec sel_rev sel_prom
  PRIOR_CTX_OUT=""
  PRIOR_PROM_HEAD=""
  sel_branch=$(_checkpoint_branch "$file")
  [ -n "$sel_branch" ] && [ "$sel_branch" != "unknown" ] && [ "$sel_branch" != "HEAD" ] || return 0
  sel_ts=$(_basename_ts "$file")
  [ -n "$sel_ts" ] || return 0
  sel_seq=$(_checkpoint_save_seq "$file")
  if _timestamp_has_cleared "$sel_ts" "$sel_branch" "$sel_seq"; then
    return 0
  fi
  sel_head=$(_checkpoint_head "$file")
  sel_dec=$(_extract_checkpoint_section "$file" decisions)
  sel_rev=$(_extract_checkpoint_section "$file" reversals)
  sel_prom=$(_extract_checkpoint_section "$file" promises)

  if [ -n "$sel_dec" ] && [ -n "$sel_rev" ] && [ -n "$sel_prom" ]; then
    return 0
  fi

  local need_dec=0 need_rev=0 need_prom=0 sparse_stub=0
  local sel_has_dec_h=0 sel_has_rev_h=0 sel_has_prom_h=0
  local sel_has_mod=0 sel_explicit_non_code=0
  [ -z "$sel_dec" ] && need_dec=1
  [ -z "$sel_rev" ] && need_rev=1
  [ -z "$sel_prom" ] && need_prom=1
  if [ "$need_dec" -eq 1 ] && [ "$need_rev" -eq 1 ]; then
    sparse_stub=1
  fi
  [ "$need_dec" -eq 1 ] && _has_section_heading "$file" decisions && sel_has_dec_h=1
  [ "$need_rev" -eq 1 ] && _has_section_heading "$file" reversals && sel_has_rev_h=1
  [ "$need_prom" -eq 1 ] && _has_section_heading "$file" promises && sel_has_prom_h=1
  _checkpoint_has_modified_files "$file" && sel_has_mod=1
  _has_explicit_non_code_stub "$file" && sel_explicit_non_code=1

  local bf_dir=""
  bf_dir=$(mktemp -d "${TMPDIR:-/tmp}/.ckpt-bf-XXXXXX" 2>/dev/null) || return 0
  _extract_checkpoint_section_to_file "$file" reversals "$bf_dir/seen_rev" 2>/dev/null || : > "$bf_dir/seen_rev"
  _extract_checkpoint_section_to_file "$file" promises "$bf_dir/sel_prom" 2>/dev/null || : > "$bf_dir/sel_prom"

  local rec_dec="" rec_rev="" rec_prom="" rec_prom_head="" src_file="" cand cand_br cand_ts cand_seq cand_head c_dec c_rev c_prom
  local sel_phys cand_phys walked=0 cand_new_rev=0 cand_cleared=0 cand_has_mod=0 cand_explicit_nc=0 rc_rev=0
  local dec_closed_head="" rev_closed_head="" prom_closed_head=""
  sel_phys=$(_phys_path "$file" || printf '%s' "$file")
  while IFS= read -r cand; do
    [ -n "$cand" ] || continue
    cand_phys=$(_phys_path "$cand" || printf '%s' "$cand")
    [ "$cand_phys" = "$sel_phys" ] && continue
    cand_br=$(_checkpoint_branch "$cand")
    [ "$cand_br" = "$sel_branch" ] || continue
    cand_ts=$(_basename_ts "$cand")
    [ -n "$cand_ts" ] || continue
    cand_seq=$(_checkpoint_save_seq "$cand")
    if ! { [[ "$cand_ts" < "$sel_ts" ]] || { [ "$cand_ts" = "$sel_ts" ] && [ "$cand_seq" -lt "$sel_seq" ]; }; }; then
      continue
    fi
    cand_cleared=0
    _checkpoint_carry_cleared "$cand" && cand_cleared=1
    if [ "$cand_cleared" -eq 0 ] && _timestamp_has_cleared "$cand_ts" "$sel_branch" "$cand_seq"; then
      continue
    fi
    walked=$((walked + 1))
    [ "$walked" -le 20 ] || break
    cand_head=$(_checkpoint_head "$cand")
    c_dec=$(_extract_checkpoint_section "$cand" decisions)
    c_rev=$(_extract_checkpoint_section "$cand" reversals)
    c_prom=$(_extract_checkpoint_section "$cand" promises)
    if [ -z "$c_dec" ] && [ -z "$c_rev" ] && [ -z "$c_prom" ]; then
      if [ "$cand_cleared" -eq 1 ]; then
        break
      fi
      if _has_explicit_non_code_stub "$cand"; then
        continue
      fi
      if _has_section_heading "$cand" any; then
        break
      fi
      continue
    fi

    : > "$bf_dir/cand_rev"
    if [ -n "$c_rev" ]; then
      _extract_checkpoint_section_to_file "$cand" reversals "$bf_dir/cand_rev" 2>/dev/null || : > "$bf_dir/cand_rev"
    fi
    cand_new_rev=0
    if [ -s "$bf_dir/seen_rev" ]; then
      rc_rev=0
      _has_new_reversal_files "$bf_dir/seen_rev" "$bf_dir/cand_rev" || rc_rev=$?
      [ "$rc_rev" -eq 0 ] && cand_new_rev=1
    fi

    if [ "$need_dec" -eq 1 ] && [ -z "$rec_dec" ] && [ -n "$c_dec" ] && [ "$cand_new_rev" -eq 0 ] \
      && { [ -z "$dec_closed_head" ] || [ "$cand_head" = "$dec_closed_head" ]; }; then
      if [ "$sel_has_dec_h" -eq 0 ] || [ "$sel_explicit_non_code" -eq 1 ] || { [ "$sel_has_mod" -eq 0 ] && [ -n "$sel_head" ] && [ "$cand_head" = "$sel_head" ]; }; then
        rec_dec="$c_dec"
        [ -n "$src_file" ] || src_file="$cand"
      fi
    fi
    if [ "$need_rev" -eq 1 ] && [ -z "$rec_rev" ] && [ -n "$c_rev" ] \
      && { [ -z "$rev_closed_head" ] || [ "$cand_head" = "$rev_closed_head" ]; }; then
      if [ "$sel_has_rev_h" -eq 0 ] || [ "$sel_explicit_non_code" -eq 1 ] || { [ "$sel_has_mod" -eq 0 ] && [ -n "$sel_head" ] && [ "$cand_head" = "$sel_head" ]; }; then
        rec_rev="$c_rev"
        [ -n "$src_file" ] || src_file="$cand"
      fi
    fi
    if [ -z "$rec_prom" ] && [ -n "$c_prom" ] && [ "$cand_new_rev" -eq 0 ] \
      && { [ -z "$prom_closed_head" ] || [ "$cand_head" = "$prom_closed_head" ]; }; then
      if [ "$need_prom" -eq 1 ]; then
        if [ "$sel_has_prom_h" -eq 0 ] || [ "$sel_explicit_non_code" -eq 1 ] || { [ "$sel_has_mod" -eq 0 ] && [ -n "$sel_head" ] && [ "$cand_head" = "$sel_head" ]; }; then
          rec_prom="$c_prom"
          rec_prom_head=$(_checkpoint_promises_head "$cand")
          [ -n "$rec_prom_head" ] || rec_prom_head="unknown"
          [ -n "$src_file" ] || src_file="$cand"
        fi
      elif [ "$sparse_stub" -eq 1 ] && { [ "$sel_explicit_non_code" -eq 1 ] || { [ "$sel_has_mod" -eq 0 ] && [ -n "$sel_head" ] && [ "$cand_head" = "$sel_head" ]; }; }; then
        _extract_checkpoint_section_to_file "$cand" promises "$bf_dir/cand_prom" 2>/dev/null || : > "$bf_dir/cand_prom"
        if _diff_only_new_items "$bf_dir/sel_prom" "$bf_dir/cand_prom" 1 "$bf_dir/only_prior_prom" && [ -s "$bf_dir/only_prior_prom" ]; then
          rec_prom=$(cat "$bf_dir/only_prior_prom")
          rec_prom_head=$(_checkpoint_promises_head "$cand")
          [ -n "$rec_prom_head" ] || rec_prom_head="unknown"
          [ -n "$src_file" ] || src_file="$cand"
        fi
      fi
    fi
    if [ -s "$bf_dir/cand_rev" ]; then
      if [ -s "$bf_dir/seen_rev" ]; then
        if _dedup_merge_files "$bf_dir/seen_rev" "$bf_dir/cand_rev" 0 "$bf_dir/seen_rev_next"; then
          mv -f "$bf_dir/seen_rev_next" "$bf_dir/seen_rev"
        fi
      else
        cp "$bf_dir/cand_rev" "$bf_dir/seen_rev"
      fi
    fi
    if [ "$cand_cleared" -eq 1 ]; then
      break
    fi
    # Track explicit section closures on intermediate non-stub checkpoints (dirty edits or moved HEAD)
    # so walking past an intermediate checkpoint never resurrects a section it explicitly closed.
    cand_explicit_nc=0
    _has_explicit_non_code_stub "$cand" && cand_explicit_nc=1
    if [ "$cand_explicit_nc" -eq 0 ]; then
      cand_has_mod=0
      _checkpoint_has_modified_files "$cand" && cand_has_mod=1
      if [ -z "$c_dec" ] && _has_section_heading "$cand" decisions; then
        if [ "$cand_has_mod" -eq 1 ]; then need_dec=0
        elif [ -n "$cand_head" ] && [ -z "$dec_closed_head" ]; then dec_closed_head="$cand_head"
        fi
      fi
      if [ -z "$c_rev" ] && _has_section_heading "$cand" reversals; then
        if [ "$cand_has_mod" -eq 1 ]; then need_rev=0
        elif [ -n "$cand_head" ] && [ -z "$rev_closed_head" ]; then rev_closed_head="$cand_head"
        fi
      fi
      if [ -z "$c_prom" ] && _has_section_heading "$cand" promises; then
        if [ "$cand_has_mod" -eq 1 ]; then need_prom=0; sparse_stub=0
        elif [ -n "$cand_head" ] && [ -z "$prom_closed_head" ]; then prom_closed_head="$cand_head"
        fi
      fi
    fi
    if { [ "$need_dec" -eq 0 ] || [ -n "$rec_dec" ]; } \
      && { [ "$need_rev" -eq 0 ] || [ -n "$rec_rev" ]; } \
      && { [ "$need_prom" -eq 0 ] || [ -n "$rec_prom" ]; }; then
      break
    fi
  done <<EOF
$MATCHED_ALL
EOF
  rm -rf "$bf_dir"

  PRIOR_PROM_HEAD="$rec_prom_head"
  if [ -n "$rec_dec" ] || [ -n "$rec_rev" ] || [ -n "$rec_prom" ]; then
    PRIOR_CTX_OUT=$({
      echo "CARRIED_FROM: $src_file"
      echo "--- PRIOR OPEN CONTEXT ---"
      if [ -n "$rec_dec" ]; then
        echo "### Active Decisions"
        printf '%s\n' "$rec_dec" | _sanitize
      fi
      if [ -n "$rec_rev" ]; then
        [ -z "$rec_dec" ] || echo ""
        echo "### Reversals / Do-Not-Repeat"
        printf '%s\n' "$rec_rev" | _sanitize
      fi
      if [ -n "$rec_prom" ]; then
        { [ -z "$rec_dec" ] && [ -z "$rec_rev" ]; } || echo ""
        echo "### Open Promises / Next Step"
        printf '%s\n' "$rec_prom" | _sanitize
      fi
      echo "--- END PRIOR OPEN CONTEXT ---"
    })
  fi
}

_emit_selected() {
  local file="$1"
  local id_tag="${2:-OK}"
  local head_out first_head
  PRIOR_CTX_OUT=""
  PRIOR_PROM_HEAD=""
  _emit_prior_open_context "$file" "$id_tag"
  echo "SELECTED_FILE: $file"
  [ "$id_tag" = "OK" ] || echo "SELECTED_IDENTITY: $id_tag"
  head_out=$(_head_check "$file" "$id_tag" "$PRIOR_PROM_HEAD")
  first_head=$(printf '%s\n' "$head_out" | head -1)
  echo "HEAD_STATUS: $first_head"
  if [ "$(printf '%s\n' "$head_out" | wc -l | tr -d ' ')" -gt 1 ]; then
    printf '%s\n' "$head_out" | tail -n +2 | _sanitize
  fi
  echo "--- CHECKPOINT ---"
  _sanitize < "$file" | awk '1'
  echo "--- END CHECKPOINT ---"
  if [ -n "$PRIOR_CTX_OUT" ]; then
    printf '%s\n' "$PRIOR_CTX_OUT"
  fi
}


MODE="${1:-}"
[ -n "$MODE" ] && shift || true

case "$MODE" in
  duration)
    _compute_duration
    echo "SESSION_DURATION_S=$SESSION_DURATION_S"
    ;;

  stamp)
    FILE="${1:-}"
    [ -n "$FILE" ] || { echo "usage: gstack-context-checkpoint stamp <file>" >&2; exit 2; }
    "$_BIN/gstack-slug" --stamp-checkpoint "$FILE" || exit $?
    echo "STAMPED"
    [ -z "${CLAUDE_PROJECT_DIR:-}" ] || "$_BIN/gstack-slug" --point-from "$CLAUDE_PROJECT_DIR" "$FILE" 2>/dev/null || true
    ;;

  head-check)
    FILE="${1:-}"
    [ -n "$FILE" ] || { echo "usage: gstack-context-checkpoint head-check <file>" >&2; exit 2; }
    _head_check "$FILE"
    ;;

  prep)
    RAW="${TITLE_RAW:-}"
    while [ $# -gt 0 ]; do
      case "$1" in
        --title) _require_arg "$1" $#; RAW="$2"; shift 2 ;;
        -*) echo "gstack-context-checkpoint prep: unknown option $1" >&2; exit 2 ;;
        *) shift ;;
      esac
    done
    RAW="${RAW:-untitled}"
    SLUG=$("$_BIN/gstack-slug" --get SLUG 2>/dev/null || echo "unknown")
    SLUG="${SLUG:-unknown}"
    CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints"
    mkdir -p "$CHECKPOINT_DIR" || exit 1
    _compute_save_path "$RAW"
    _compute_duration
    BRANCH=$(_current_branch)
    BRANCH="${BRANCH:-unknown}"
    ISO_TS=$(_iso_timestamp)
    echo "CHECKPOINT_DIR=$CHECKPOINT_DIR"
    echo "TIMESTAMP=$TIMESTAMP"
    echo "ISO_TIMESTAMP=$ISO_TS"
    echo "TITLE_SLUG=$TITLE_SLUG"
    echo "FILE=$FILE"
    echo "BRANCH=$BRANCH"
    echo "SESSION_DURATION_S=$SESSION_DURATION_S"
    MOD_LINES=$(git status --short 2>/dev/null | head -20 || true)
    if [ -n "$MOD_LINES" ]; then
      echo "MODIFIED_FILES:"
      printf '%s\n' "$MOD_LINES"
    fi
    ;;

  save)
    RAW="${TITLE_RAW:-}"
    STATUS="in-progress"
    BODY_FILE=""
    EXPLICIT_CARRY=0
    CLEAR_CARRY=0
    while [ $# -gt 0 ]; do
      case "$1" in
        --title) _require_arg "$1" $#; RAW="$2"; shift 2 ;;
        --status) _require_arg "$1" $#; STATUS="$2"; shift 2 ;;
        --body-file) _require_arg "$1" $#; BODY_FILE="$2"; shift 2 ;;
        --carry-forward) EXPLICIT_CARRY=1; shift ;;
        --replace|--clear) CLEAR_CARRY=1; shift ;;
        -*) echo "gstack-context-checkpoint save: unknown option $1" >&2; exit 2 ;;
        *) shift ;;
      esac
    done
    if [ "$EXPLICIT_CARRY" -eq 1 ] && [ "$CLEAR_CARRY" -eq 1 ]; then
      echo "gstack-context-checkpoint save: cannot combine --carry-forward with --replace/--clear" >&2
      exit 2
    fi
    STATUS=$(printf '%s' "$STATUS" | tr -cd 'a-zA-Z0-9_-')
    STATUS="${STATUS:-in-progress}"
    _resolve_timestamp
    SLUG=$("$_BIN/gstack-slug" --get SLUG 2>/dev/null || echo "unknown")
    SLUG="${SLUG:-unknown}"
    CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints"
    mkdir -p "$CHECKPOINT_DIR" || { echo "gstack-context-checkpoint: cannot create $CHECKPOINT_DIR" >&2; exit 1; }
    _compute_duration
    BRANCH=$(_current_branch)
    BRANCH="${BRANCH:-unknown}"
    ISO_TS=$(_iso_timestamp)

    BODY_TMP=$(mktemp "${CHECKPOINT_DIR}/.body-XXXXXX") || exit 1
    CARRY_TMP=""
    OUT_TMP=$(mktemp "${CHECKPOINT_DIR}/.out-XXXXXX") || { rm -f "$BODY_TMP"; exit 1; }
    LOCK_FILE=""
    trap 'rm -f "$BODY_TMP" "${CARRY_TMP:-}" "$OUT_TMP" "${LOCK_FILE:-}"' EXIT

    if [ -n "$BODY_FILE" ]; then
      if [ ! -f "$BODY_FILE" ] || [ ! -r "$BODY_FILE" ]; then
        echo "gstack-context-checkpoint: unreadable --body-file: $BODY_FILE" >&2
        exit 2
      fi
      tr -d '\r' < "$BODY_FILE" > "$BODY_TMP" || { echo "gstack-context-checkpoint: failed reading $BODY_FILE" >&2; exit 1; }
    else
      if [ -t 0 ]; then
        echo "gstack-context-checkpoint: empty checkpoint body (pipe body on stdin or pass --body-file)" >&2
        exit 2
      fi
      tr -d '\r' > "$BODY_TMP" || { echo "gstack-context-checkpoint: failed reading checkpoint body from stdin" >&2; exit 1; }
    fi

    if ! grep -q '[^[:space:]]' "$BODY_TMP" 2>/dev/null; then
      echo "gstack-context-checkpoint: refusing to save empty checkpoint body" >&2
      exit 2
    fi

    # Derive title from body heading when TITLE_RAW / --title was not provided.
    if [ -z "$RAW" ]; then
      RAW=$(_body_title "$BODY_TMP")
    fi
    RAW="${RAW:-untitled}"
    _compute_save_path "$RAW"

    ALL_MOD_FILES=$(git status --short 2>/dev/null | sed 's/^...//; s/.* -> //' | grep -v '^[[:space:]]*$' || true)
    MOD_COUNT=0
    MOD_FILES=""
    if [ -n "$ALL_MOD_FILES" ]; then
      MOD_COUNT=$(printf '%s\n' "$ALL_MOD_FILES" | wc -l | tr -d ' ')
      MOD_FILES=$(printf '%s\n' "$ALL_MOD_FILES" | head -30)
    fi

    # Assign a monotonically increasing same-second save_seq when another checkpoint
    # already shares TIMESTAMP, preserving exact publication order across same-second saves/clears.
    SAVE_SEQ=0
    for _same_ts_f in "$CHECKPOINT_DIR/${TIMESTAMP}"-*.md; do
      [ -e "$_same_ts_f" ] || break
      _f_seq=$(_checkpoint_save_seq "$_same_ts_f")
      if [ "${_f_seq:-0}" -ge "$SAVE_SEQ" ] 2>/dev/null; then
        SAVE_SEQ=$((_f_seq + 1))
      fi
    done

    # Carry forward open Active Decisions, Reversals / Do-Not-Repeat, and Open Promises / Next Step
    # from the prior verified same-branch checkpoint unless --replace/--clear was passed.
    # Fast single-grep pre-check avoids classifying the bucket when no prior file has structured sections.
    CARRIED_FROM=""
    CARRIED_PROMISES=0
    MIXED_PROMISES=0
    CARRIED_PROMISES_HEAD=""
    BODY_BRANCH=$(_checkpoint_branch "$BODY_TMP")
    if [ "$CLEAR_CARRY" -eq 0 ] && [ -n "$BRANCH" ] && [ "$BRANCH" != "unknown" ] && [ "$BRANCH" != "HEAD" ] \
      && { [ -z "$BODY_BRANCH" ] || [ "$BODY_BRANCH" = "$BRANCH" ]; } \
      && grep -qiE '^###?[[:space:]]+(active decisions|decisions made|reversals|open promises|next step|remaining work)' "$CHECKPOINT_DIR"/*.md 2>/dev/null; then
      CURRENT_BRANCH="$BRANCH"
      _discover_checkpoints 0 1
      if [ "$IDENTITY_STATE" = "OK" ] && [ -n "$MATCHED_ALL" ] && ! _timestamp_has_cleared "$TIMESTAMP" "$BRANCH" "$SAVE_SEQ"; then
        CURR_HEAD=$(git rev-parse --verify -q HEAD 2>/dev/null || true)
        PREV_CAND=""
        _cf_walked=0
        while IFS= read -r cf; do
          [ -n "$cf" ] || continue
          cf_br=$(_checkpoint_branch "$cf")
          [ "$cf_br" = "$BRANCH" ] || continue
          cf_ts=$(_basename_ts "$cf")
          [ -n "$cf_ts" ] || continue
          cf_seq=$(_checkpoint_save_seq "$cf")
          if ! { [[ "$cf_ts" < "$TIMESTAMP" ]] || { [ "$cf_ts" = "$TIMESTAMP" ] && [ "$cf_seq" -lt "$SAVE_SEQ" ]; }; }; then
            continue
          fi
          cf_cleared=0
          _checkpoint_carry_cleared "$cf" && cf_cleared=1
          if [ "$cf_cleared" -eq 0 ] && _timestamp_has_cleared "$cf_ts" "$BRANCH" "$cf_seq"; then
            continue
          fi
          _cf_walked=$((_cf_walked + 1))
          [ "$_cf_walked" -le 20 ] || break
          if [ -n "$(_extract_checkpoint_section "$cf" decisions)" ] \
            || [ -n "$(_extract_checkpoint_section "$cf" reversals)" ] \
            || [ -n "$(_extract_checkpoint_section "$cf" promises)" ]; then
            PREV_CAND="$cf"
            break
          fi
          if [ "$cf_cleared" -eq 1 ]; then
            break
          fi
          if _has_explicit_non_code_stub "$cf"; then
            continue
          fi
          if _has_section_heading "$cf" any; then
            break
          fi
        done <<EOF
$MATCHED_ALL
EOF
        if [ -n "$PREV_CAND" ]; then
          IS_NON_CODE=0
          PREV_HEAD=$(_checkpoint_head "$PREV_CAND")
          if { [ "$MOD_COUNT" -eq 0 ] && ! _checkpoint_has_modified_files "$BODY_TMP" && [ -n "$CURR_HEAD" ] && [ "$PREV_HEAD" = "$CURR_HEAD" ]; } \
            || _has_explicit_non_code_stub "$BODY_TMP"; then
            IS_NON_CODE=1
          fi
          CARRY_TMP=$(mktemp "${CHECKPOINT_DIR}/.carry-XXXXXX") || exit 1
          _cf_rc=0
          _apply_carry_forward "$BODY_TMP" "$PREV_CAND" "$IS_NON_CODE" "$EXPLICIT_CARRY" "$CARRY_TMP" || _cf_rc=$?
          if [ "$_cf_rc" -eq 0 ]; then
            mv -f "$CARRY_TMP" "$BODY_TMP"
            CARRY_TMP=""
            CARRIED_FROM="$PREV_CAND"
            if [ "$CARRIED_PROMISES" -eq 1 ]; then
              PROM_SRC_HEAD=$(_checkpoint_promises_head "$PREV_CAND")
              if [ -z "$PROM_SRC_HEAD" ]; then
                CARRIED_PROMISES_HEAD="unknown"
              elif [ "$MIXED_PROMISES" -eq 1 ] && [ "$PROM_SRC_HEAD" != "$CURR_HEAD" ]; then
                CARRIED_PROMISES_HEAD="unknown"
              else
                CARRIED_PROMISES_HEAD="$PROM_SRC_HEAD"
              fi
            fi
          elif [ "$_cf_rc" -ge 2 ]; then
            rm -f "$CARRY_TMP"
            CARRY_TMP=""
            echo "gstack-context-checkpoint: failed merging prior open context (aborting save)" >&2
            exit 1
          else
            rm -f "$CARRY_TMP"
            CARRY_TMP=""
          fi
        fi
      fi
    fi

    FIRST_LINE=$(head -n 1 "$BODY_TMP" 2>/dev/null | tr -d '\r' || true)
    if [ "$FIRST_LINE" = "---" ] && awk 'NR>1 && /^---[[:space:]]*$/ { f=1; exit } END { exit !f }' "$BODY_TMP" 2>/dev/null; then
      HAS_STATUS=$(awk 'NR==1{fm=1;next} fm&&/^---/{exit} fm&&/^status:/{f=1} END{print f+0}' "$BODY_TMP")
      HAS_BRANCH=$(awk 'NR==1{fm=1;next} fm&&/^---/{exit} fm&&/^branch:/{f=1} END{print f+0}' "$BODY_TMP")
      HAS_TS=$(awk 'NR==1{fm=1;next} fm&&/^---/{exit} fm&&/^timestamp:/{f=1} END{print f+0}' "$BODY_TMP")
      HAS_DUR=$(awk 'NR==1{fm=1;next} fm&&/^---/{exit} fm&&/^session_duration_s:/{f=1} END{print f+0}' "$BODY_TMP")
      HAS_MOD=$(awk 'NR==1{fm=1;next} fm&&/^---/{exit} fm&&/^files_modified:/{f=1} END{print f+0}' "$BODY_TMP")
      GSTACK_MOD_FILES="$MOD_FILES" awk -v st="$STATUS" -v br="$BRANCH" -v ts="$ISO_TS" -v dur="$SESSION_DURATION_S" \
          -v hst="$HAS_STATUS" -v hbr="$HAS_BRANCH" -v hts="$HAS_TS" -v hdur="$HAS_DUR" \
          -v hmod="$HAS_MOD" -v cclr="$CLEAR_CARRY" -v cph="$CARRIED_PROMISES_HEAD" -v sseq="$SAVE_SEQ" '
        NR == 1 { infm = 1; print; next }
        infm && /^---[[:space:]]*$/ {
          if (!hst) print "status: " st
          if (!hbr) print "branch: " br
          if (!hts) print "timestamp: " ts
          if (!hdur && dur != "unknown") print "session_duration_s: " dur
          if (sseq > 0) print "save_seq: " sseq
          if (cclr) print "carry_forward: cleared"
          if (cph != "") print "carried_promises_head: " cph
          modfiles = ENVIRON["GSTACK_MOD_FILES"]
          if (!hmod && modfiles != "") {
            print "files_modified:"
            n = split(modfiles, arr, "\n")
            for (i = 1; i <= n; i++) if (arr[i] != "") print "  - " arr[i]
          }
          print
          infm = 0
          next
        }
        infm && (/^remote:/ || /^project_root:/ || /^worktree:/ || /^head:/ || /^carried_promises_head:/ || /^save_seq:/ || (cclr && /^carry_forward:/)) { next }
        { print }
      ' "$BODY_TMP" > "$OUT_TMP" || { echo "gstack-context-checkpoint: failed to assemble checkpoint" >&2; exit 1; }
    else
      {
        echo "---"
        echo "status: $STATUS"
        echo "branch: $BRANCH"
        echo "timestamp: $ISO_TS"
        [ "$SESSION_DURATION_S" = "unknown" ] || echo "session_duration_s: $SESSION_DURATION_S"
        [ "$SAVE_SEQ" -eq 0 ] || echo "save_seq: $SAVE_SEQ"
        [ "$CLEAR_CARRY" -eq 0 ] || echo "carry_forward: cleared"
        [ -z "$CARRIED_PROMISES_HEAD" ] || echo "carried_promises_head: $CARRIED_PROMISES_HEAD"
        if [ -n "$MOD_FILES" ]; then
          echo "files_modified:"
          printf '%s\n' "$MOD_FILES" | sed 's/^/  - /'
        fi
        echo "---"
        echo ""
        cat "$BODY_TMP"
      } > "$OUT_TMP" || { echo "gstack-context-checkpoint: failed to assemble checkpoint" >&2; exit 1; }
    fi

    # Stamp the temporary file BEFORE atomic publication so no unstamped checkpoint is ever visible.
    chmod 600 "$OUT_TMP" 2>/dev/null || true
    "$_BIN/gstack-slug" --stamp-checkpoint "$OUT_TMP" || { echo "gstack-context-checkpoint: failed to stamp checkpoint" >&2; exit 1; }
    chmod 600 "$OUT_TMP" 2>/dev/null || true

    # Atomic non-overwriting publish (append-only guarantee under concurrent saves).
    PUBLISHED=0
    _try=0
    while [ "$_try" -lt 16 ]; do
      if [ "$_try" -gt 0 ]; then
        _compute_save_path "$RAW" 1
      fi
      if ln "$OUT_TMP" "$FILE" 2>/dev/null; then
        PUBLISHED=1
        break
      fi
      # If destination does not exist, ln failed for a non-EEXIST reason (e.g. FS without hardlinks).
      [ -e "$FILE" ] || break
      _try=$((_try + 1))
    done
    if [ "$PUBLISHED" -eq 0 ]; then
      # Fallback when hardlinks are unsupported: reserve a hidden dot-lock with noclobber
      # (invisible to *.md discovery), then atomically rename the stamped 0600 temp file.
      _try=0
      while [ "$_try" -lt 16 ]; do
        [ "$_try" -eq 0 ] || _compute_save_path "$RAW" 1
        CAND_LOCK="${CHECKPOINT_DIR}/.$(basename "$FILE").lock"
        if ( set -o noclobber; : > "$CAND_LOCK" ) 2>/dev/null; then
          LOCK_FILE="$CAND_LOCK"
          if [ ! -e "$FILE" ] && mv "$OUT_TMP" "$FILE" 2>/dev/null; then
            PUBLISHED=1
            rm -f "$LOCK_FILE"
            LOCK_FILE=""
            break
          fi
          rm -f "$LOCK_FILE"
          LOCK_FILE=""
        fi
        _try=$((_try + 1))
      done
    fi
    if [ "$PUBLISHED" -eq 0 ]; then
      echo "gstack-context-checkpoint: failed to publish unique checkpoint file" >&2
      exit 1
    fi

    rm -f "$BODY_TMP" "${CARRY_TMP:-}" "$OUT_TMP"
    trap - EXIT

    [ -z "${CLAUDE_PROJECT_DIR:-}" ] || "$_BIN/gstack-slug" --point-from "$CLAUDE_PROJECT_DIR" "$FILE" 2>/dev/null || true

    echo "CHECKPOINT_DIR=$CHECKPOINT_DIR"
    echo "TIMESTAMP=$TIMESTAMP"
    echo "TITLE_SLUG=$TITLE_SLUG"
    echo "FILE=$FILE"
    echo "BRANCH=$BRANCH"
    echo "MODIFIED=$MOD_COUNT"
    echo "SESSION_DURATION_S=$SESSION_DURATION_S"
    [ -z "$CARRIED_FROM" ] || echo "CARRIED_FORWARD_FROM=$CARRIED_FROM"
    echo "STAMPED"
    ;;

  restore)
    NO_READ=0
    FRAG="${FRAGMENT:-}"
    FRAG_STDIN=0
    FILE_STDIN=0
    EXPLICIT_FILE=""
    while [ $# -gt 0 ]; do
      case "$1" in
        --no-read) NO_READ=1; shift ;;
        --fragment) _require_arg "$1" $#; FRAG="$2"; shift 2 ;;
        --fragment-stdin) FRAG_STDIN=1; shift ;;
        --file) _require_arg "$1" $#; EXPLICIT_FILE="$2"; shift 2 ;;
        --file-stdin) FILE_STDIN=1; shift ;;
        -*) echo "gstack-context-checkpoint restore: unknown option $1" >&2; exit 2 ;;
        *) [ -z "$FRAG" ] && FRAG="$1"; shift ;;
      esac
    done
    if [ "$FRAG_STDIN" -eq 1 ] && [ "$FILE_STDIN" -eq 1 ]; then
      echo "gstack-context-checkpoint restore: cannot combine --fragment-stdin and --file-stdin" >&2
      exit 2
    fi
    if [ "$FRAG_STDIN" -eq 1 ]; then
      if [ -t 0 ]; then
        echo "gstack-context-checkpoint restore: --fragment-stdin requires stdin" >&2
        exit 2
      fi
      FRAG=$(cat | tr -d '\r' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' | head -n 1)
    fi
    if [ "$FILE_STDIN" -eq 1 ]; then
      if [ -t 0 ]; then
        echo "gstack-context-checkpoint restore: --file-stdin requires stdin" >&2
        exit 2
      fi
      EXPLICIT_FILE=$(cat | tr -d '\r' | head -n 1)
    fi

    _resolve_project_identity
    echo "PROJECT_IDENTITY: ${PROJECT_REMOTE:-${PROJECT_ROOT:-unknown}}"
    echo "PROJECT_ROOT: ${PROJECT_ROOT:-unknown}"
    if [ -n "${LEGACY_SLUG:-}" ] && [ -d "$GSTACK_STATE_ROOT/projects/$LEGACY_SLUG/checkpoints" ]; then
      LEGACY_N=$(find "$GSTACK_STATE_ROOT/projects/$LEGACY_SLUG/checkpoints" -maxdepth 1 -name "*.md" -type f 2>/dev/null | wc -l | tr -d ' ')
      if [ "$LEGACY_N" -gt 0 ]; then
        echo "LEGACY_BUCKET: projects/$LEGACY_SLUG holds $LEGACY_N earlier checkpoint(s) from the bucket this project shared with other nested-group repos; review and copy with: $_BIN/gstack-slug --adopt-legacy"
      fi
    fi

    : "${CURRENT_BRANCH:=$(_current_branch)}"
    # Scan the whole bucket consistently across restore, fragment/index picks, and list so
    # FOREIGN_N and 1-based numbering never diverge when a bucket exceeds 200 saves.
    _discover_checkpoints 0

    NEWER_TASK_LINES=""
    VERIFIED_FILES=""
    BELOW_LINES=$("$_BIN/gstack-slug" --checkpoints-below 2>/dev/null || true)
    if [ -z "$EXPLICIT_FILE" ]; then
      if [ "$IDENTITY_STATE" = "EMPTY" ]; then
        echo "NO_CHECKPOINTS"
      elif [ "$IDENTITY_STATE" = "FAILED" ]; then
        echo "IDENTITY_CHECK_FAILED"
        printf '%s\n' "$UNVERIFIED_LINES" | head -20
      else
        if [ -n "$VERIFIED_ALL" ]; then
          VERIFIED_FILES=$(printf '%s\n' "$VERIFIED_ALL" | head -20)
          printf '%s\n' "$VERIFIED_FILES"
          NEWER_TASK_LINES=$(printf '%s\n' "$VERIFIED_ALL" | "$_BIN/gstack-slug" --newer-task "$CURRENT_BRANCH" 2>/dev/null || true)
          [ -z "$NEWER_TASK_LINES" ] || printf '%s\n' "$NEWER_TASK_LINES"
        else
          echo "NO_VERIFIED_CHECKPOINTS"
        fi
        PREFIXED_OUT=""
        [ -z "$ROOT_DIFFERS_LINES" ] || PREFIXED_OUT="${PREFIXED_OUT:+${PREFIXED_OUT}
}${ROOT_DIFFERS_LINES}"
        [ -z "$FOREIGN_LINES" ] || PREFIXED_OUT="${PREFIXED_OUT:+${PREFIXED_OUT}
}${FOREIGN_LINES}"
        [ -z "$UNVERIFIED_LINES" ] || PREFIXED_OUT="${PREFIXED_OUT:+${PREFIXED_OUT}
}${UNVERIFIED_LINES}"
        [ -z "$PREFIXED_OUT" ] || printf '%s\n' "$PREFIXED_OUT" | head -40
        if [ "$FOREIGN_N" -gt 0 ]; then
          echo "SHARED_BUCKET: $FOREIGN_N checkpoint(s) here were saved by another project"
        fi
      fi
      [ -z "$BELOW_LINES" ] || printf '%s\n' "$BELOW_LINES"
    fi

    [ "$NO_READ" -eq 0 ] || exit 0

    if [ -n "$EXPLICIT_FILE" ]; then
      STATE_PHYS=$(cd "$GSTACK_STATE_ROOT" 2>/dev/null && pwd -P) || STATE_PHYS="$GSTACK_STATE_ROOT"
      EXP_DIR=$(cd "$(dirname "$EXPLICIT_FILE")" 2>/dev/null && pwd -P) || EXP_DIR=""
      if [ -f "$EXPLICIT_FILE" ] && [ ! -L "$EXPLICIT_FILE" ] \
         && [ "$(basename "$EXP_DIR")" = "checkpoints" ] \
         && [ "$(dirname "$(dirname "$EXP_DIR")")" = "$STATE_PHYS/projects" ]; then
        EXP_PHYS=$(_phys_path "$EXPLICIT_FILE" || printf '%s' "$EXPLICIT_FILE")
        CHECKPOINT_DIR_PHYS=$(cd "$CHECKPOINT_DIR" 2>/dev/null && pwd -P) || CHECKPOINT_DIR_PHYS=""
        IS_BELOW=0
        if [ -n "$BELOW_LINES" ]; then
          while IFS= read -r bl; do
            [ -n "$bl" ] || continue
            bpath=${bl#* }
            bphys=$(_phys_path "$bpath" || printf '%s' "$bpath")
            if [ "$bphys" = "$EXP_PHYS" ] && _is_below_cwd "$EXPLICIT_FILE"; then
              IS_BELOW=1
              break
            fi
          done <<EOF
$BELOW_LINES
EOF
        fi
        if [ "$IS_BELOW" -eq 1 ]; then
          EXP_TAG="BELOW"
        else
          EXP_CLS=$(printf '%s\n' "$EXPLICIT_FILE" | "$_BIN/gstack-slug" --classify-checkpoints 2>/dev/null | cut -f1)
          case "$EXP_CLS" in
            match) EXP_TAG="OK" ;;
            match-root) EXP_TAG="ROOT_DIFFERS" ;;
            foreign) EXP_TAG="FOREIGN" ;;
            unstamped)
              if [ -n "$CHECKPOINT_DIR_PHYS" ] && [ "$EXP_DIR" = "$CHECKPOINT_DIR_PHYS" ] \
                 && [ "$FOREIGN_N" -eq 0 ] && [ "$IDENTITY_STATE" != "FAILED" ]; then
                EXP_TAG="OK"
              else
                EXP_TAG="UNVERIFIED"
              fi
              ;;
            *) EXP_TAG="IDENTITY_CHECK_FAILED" ;;
          esac
        fi
        _emit_selected "$EXPLICIT_FILE" "$EXP_TAG"
      else
        echo "FILE_NOT_FOUND: $EXPLICIT_FILE"
        exit 1
      fi
      exit 0
    fi

    if [ -n "$FRAG" ]; then
      # Candidate pool uses the EXACT same verified ordering as list/list --all (all verified
      # checkpoints without the 20-line display cap), followed by BELOW_CWD/POINTER, FOREIGN,
      # and UNVERIFIED so both numeric picks and fragment matches stay consistent.
      POOL_PATHS=""
      if [ -n "$VERIFIED_ALL" ]; then
        POOL_PATHS=$(printf '%s\n' "$CLASSIFIED" | awk -F '\t' -v f="$FOREIGN_N" '
          $1 == "match" || ($1 == "unstamped" && f == 0) { print "OK\t" $2 }
          $1 == "match-root" { print "ROOT_DIFFERS\t" $2 }
        ')
      fi
      if [ -n "$BELOW_LINES" ]; then
        while IFS= read -r bl; do
          [ -n "$bl" ] || continue
          bpath=${bl#* }
          if _is_below_cwd "$bpath"; then
            btag="BELOW"
          else
            bcls=$(printf '%s\n' "$bpath" | "$_BIN/gstack-slug" --classify-checkpoints 2>/dev/null | cut -f1)
            case "$bcls" in
              match) btag="OK" ;;
              match-root) btag="ROOT_DIFFERS" ;;
              foreign) btag="FOREIGN" ;;
              unstamped) btag="UNVERIFIED" ;;
              *) btag="IDENTITY_CHECK_FAILED" ;;
            esac
          fi
          POOL_PATHS="${POOL_PATHS:+${POOL_PATHS}
}${btag}${_TAB}${bpath}"
        done <<EOF
$BELOW_LINES
EOF
      fi
      if [ -n "$FOREIGN_LINES" ]; then
        FP=$(printf '%s\n' "$FOREIGN_LINES" | sed "s/^FOREIGN /FOREIGN${_TAB}/")
        POOL_PATHS="${POOL_PATHS:+${POOL_PATHS}
}${FP}"
      fi
      if [ -n "$UNVERIFIED_LINES" ]; then
        UP=$(printf '%s\n' "$UNVERIFIED_LINES" | sed "s/^UNVERIFIED /UNVERIFIED${_TAB}/")
        POOL_PATHS="${POOL_PATHS:+${POOL_PATHS}
}${UP}"
      fi
      if [ -z "$POOL_PATHS" ]; then
        echo "FRAGMENT_NOT_FOUND: $FRAG"
        exit 0
      fi
      case "$FRAG" in
        *[!0-9]*)
          FRAG_LC=$(printf '%s' "$FRAG" | tr '[:upper:]' '[:lower:]')
          MATCHES=""
          MATCH_N=0
          while IFS="$_TAB" read -r tag fpath; do
            [ -n "$fpath" ] || continue
            bname_lc=$(basename "$fpath" | tr '[:upper:]' '[:lower:]')
            title_lc=$(_checkpoint_title "$fpath" | tr '[:upper:]' '[:lower:]')
            case "$bname_lc" in
              *"$FRAG_LC"*) matched=1 ;;
              *)
                case "$title_lc" in
                  *"$FRAG_LC"*) matched=1 ;;
                  *) matched=0 ;;
                esac
                ;;
            esac
            if [ "$matched" -eq 1 ]; then
              MATCH_N=$((MATCH_N + 1))
              MATCHES="${MATCHES:+${MATCHES}
}${tag}${_TAB}${fpath}"
            fi
          done <<EOF
$POOL_PATHS
EOF
          if [ "$MATCH_N" -eq 0 ]; then
            echo "FRAGMENT_NOT_FOUND: $FRAG"
          elif [ "$MATCH_N" -eq 1 ]; then
            SEL_TAG=$(printf '%s' "$MATCHES" | cut -f1)
            SEL_PATH=$(printf '%s' "$MATCHES" | cut -f2-)
            _emit_selected "$SEL_PATH" "$SEL_TAG"
          else
            echo "AMBIGUOUS: multiple-fragment-matches"
            printf '%s\n' "$MATCHES" | while IFS="$_TAB" read -r tag fpath; do
              echo "MATCH: $fpath ($(_checkpoint_title "$fpath"))"
            done
          fi
          ;;
        *)
          if [ "$FRAG" -ge 1 ] 2>/dev/null; then
            PICK=$(printf '%s\n' "$POOL_PATHS" | sed -n "${FRAG}p")
            if [ -n "$PICK" ]; then
              SEL_TAG=$(printf '%s' "$PICK" | cut -f1)
              SEL_PATH=$(printf '%s' "$PICK" | cut -f2-)
              _emit_selected "$SEL_PATH" "$SEL_TAG"
            else
              echo "FRAGMENT_NOT_FOUND: $FRAG"
            fi
          else
            echo "FRAGMENT_NOT_FOUND: $FRAG"
          fi
          ;;
      esac
      exit 0
    fi

    if [ "$IDENTITY_STATE" != "OK" ] || [ -z "$VERIFIED_FILES" ]; then
      if [ -n "$BELOW_LINES" ]; then
        echo "AMBIGUOUS: below-cwd-or-pointer"
      fi
      exit 0
    fi

    FIRST_FILE=$(printf '%s\n' "$VERIFIED_FILES" | head -1)

    if [ -n "$NEWER_TASK_LINES" ]; then
      echo "AMBIGUOUS: newer-task"
      exit 0
    fi

    if [ -n "$BELOW_LINES" ]; then
      FIRST_TS=$(_basename_ts "$FIRST_FILE")
      NEWER_BELOW=0
      while IFS= read -r bl; do
        [ -n "$bl" ] || continue
        bpath=${bl#* }
        bts=$(_basename_ts "$bpath")
        if [ -n "$bts" ] && { [ -z "$FIRST_TS" ] || [[ "$bts" > "$FIRST_TS" ]]; }; then
          NEWER_BELOW=1
          break
        fi
      done <<EOF
$BELOW_LINES
EOF
      if [ "$NEWER_BELOW" -eq 1 ]; then
        echo "AMBIGUOUS: below-cwd-or-pointer"
        exit 0
      fi
    fi

    if [ -z "$CURRENT_BRANCH" ] || [ "$CURRENT_BRANCH" = "HEAD" ]; then
      TOP3=$(printf '%s\n' "$VERIFIED_FILES" | head -3)
      FIRST_NORM=""
      DIFF_TITLE=0
      while IFS= read -r f; do
        [ -n "$f" ] || continue
        nt=$(_norm_title "$(_checkpoint_title "$f")")
        if [ -z "$FIRST_NORM" ]; then
          FIRST_NORM="$nt"
        elif [ "$nt" != "$FIRST_NORM" ]; then
          DIFF_TITLE=1
          break
        fi
      done <<EOF
$TOP3
EOF
      if [ "$DIFF_TITLE" -eq 1 ]; then
        echo "AMBIGUOUS: no-branch-discriminator"
        exit 0
      fi
    fi

    FIRST_TAG="OK"
    if printf '%s\n' "$ROOT_DIFFERS_LINES" | grep -qxF "ROOT_DIFFERS $FIRST_FILE"; then
      FIRST_TAG="ROOT_DIFFERS"
    fi
    _emit_selected "$FIRST_FILE" "$FIRST_TAG"
    ;;

  list)
    SHOW_ALL=0
    DISPLAY_LIMIT=200
    while [ $# -gt 0 ]; do
      case "$1" in
        --all) SHOW_ALL=1; shift ;;
        -*) echo "gstack-context-checkpoint list: unknown option $1" >&2; exit 2 ;;
        *) shift ;;
      esac
    done
    _resolve_project_identity
    : "${CURRENT_BRANCH:=$(_current_branch)}"
    # Scan every file in the bucket (no pre-filter truncation) and share restore's
    # verified, current-branch-first ordering so row numbers match `restore <N>` 1-to-1.
    _discover_checkpoints 0
    if [ "$IDENTITY_STATE" = "EMPTY" ]; then
      echo "NO_CHECKPOINTS"
      exit 0
    fi
    if [ "$IDENTITY_STATE" = "FAILED" ]; then
      echo "IDENTITY_CHECK_FAILED"
      exit 1
    fi
    UNVERIFIED_N=0
    [ -z "$UNVERIFIED_LINES" ] || UNVERIFIED_N=$(printf '%s\n' "$UNVERIFIED_LINES" | grep -c '^UNVERIFIED ' || true)
    HIDDEN_N=$((FOREIGN_N + UNVERIFIED_N))
    if [ -z "$VERIFIED_ALL" ]; then
      echo "NO_VERIFIED_CHECKPOINTS"
      [ "$HIDDEN_N" -eq 0 ] || echo "HIDDEN: $HIDDEN_N other-project/unverified"
      exit 0
    fi
    echo "CHECKPOINT_DIR=$CHECKPOINT_DIR"
    echo "CURRENT_BRANCH=${CURRENT_BRANCH:-unknown}"
    [ "$HIDDEN_N" -eq 0 ] || echo "HIDDEN: $HIDDEN_N other-project/unverified"
    printf '%s\n' "$VERIFIED_ALL" | GSTACK_CUR_BR="$CURRENT_BRANCH" awk -v show_all="$SHOW_ALL" -v limit="$DISPLAY_LIMIT" '
      BEGIN { cur = ENVIRON["GSTACK_CUR_BR"]; total = 0; shown = 0 }
      $0 == "" { next }
      {
        f = $0; b = ""; s = ""; t = ""; fm = 0; ln = 0
        while ((getline line < f) > 0) {
          ln++
          sub(/\r$/, "", line)
          if (ln == 1) {
            if (line == "---") { fm = 1; continue }
            break
          }
          if (fm && line == "---") break
          if (fm && line ~ /^branch:/ && b == "") { sub(/^branch:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); b = line }
          else if (fm && line ~ /^status:/ && s == "") { sub(/^status:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); s = line }
          else if (fm && line ~ /^timestamp:/ && t == "") { sub(/^timestamp:[ \t]*/, "", line); sub(/[ \t]+$/, "", line); t = line }
        }
        close(f)
        if (!show_all && cur != "" && b != cur) next
        total++
        if (shown >= limit) next
        shown++
        n = split(f, segs, "/")
        fname = segs[n]
        bname = fname
        sub(/\.md$/, "", bname)
        date_part = (length(t) >= 10) ? substr(t, 1, 10) : ""
        if (date_part == "" && bname ~ /^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-/) {
          date_part = substr(bname, 1, 4) "-" substr(bname, 5, 2) "-" substr(bname, 7, 2)
        }
        if (date_part == "") date_part = "unknown"
        title_part = bname
        sub(/^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]-?/, "", title_part)
        if (s == "") s = "in-progress"
        if (b == "") b = "unknown"
        if (show_all) printf "%d\t%s\t%s\t%s\t%s\t%s\n", total, date_part, title_part, b, s, fname
        else printf "%d\t%s\t%s\t%s\t%s\n", total, date_part, title_part, s, fname
      }
      END {
        if (total == 0) printf "NO_CHECKPOINTS_ON_BRANCH: %s\n", (cur != "" ? cur : "unknown")
        else if (total > limit) printf "TRUNCATED: showing %d of %d\n", limit, total
      }
    '
    ;;

  *)
    echo "usage: gstack-context-checkpoint <save|prep|stamp|duration|head-check|restore|list> [args...]" >&2
    exit 2
    ;;
esac
