#!/bin/bash
# worktree-dirty-check.sh — shared dirty-worktree detection.
#
# Single source of truth for "does this worktree have real changes?"
# (one implementation, callers delegate — see .claude/rules/maintainability.md).
#
# Callers:
#   - bin/mux worktree_cleanup()   (interactive `mux worktree cleanup`)
#   - worktree-cleanup.sh          (fire-and-forget tmux pane-exited hook,
#                                   which SILENTLY DELETES clean worktrees)
#
# Usage:
#   worktree-dirty-check.sh <wt_path> <proj_path>
#
# stdout (single line, space-separated key=value):
#   commits=<n|?> uncommitted=<n|?> verdict=<clean|dirty>
#
# Exit code: 0 whenever a verdict line was printed (even verdict=dirty), so
# `set -e` callers can command-substitute safely; 2 only on usage error.
#
# FAIL-DIRTY SEMANTICS: any count that cannot be determined is reported as
# "?" and forces verdict=dirty. A worktree is never classified clean — and
# therefore never deleted — on the strength of a failed check. Callers must
# apply the same rule when this helper itself is missing or its output is
# unparseable: degrade to dirty, never abort silently and never delete.
#
# EXCLUSION CONTRACT (shell side) ---------------------------------------------
# The dirty verdict ignores ONLY known CC-infrastructure churn that mux
# itself manufactures in every worktree:
#
#   1. Untracked .claude/ infra — mux copies .claude/ (skills, agents,
#      settings) into each worktree; git-exclude rules hide most of it, but
#      an untracked `.claude/` dir or stray infra file is still churn.
#      EXCEPTION: untracked files under any top-level .claude/ entry that
#      holds TRACKED files (plans/, methodology/, rules/, cabinet/, …) are
#      AUTHORED PROJECT RECORD (.claude/rules/artifacts-of-thought.md) and
#      always count as dirty. The authored set is derived from the worktree's
#      index at run time; if it can't be read, the static plans/methodology
#      floor applies (fail-dirty, never fail-clean).
#
#   2. .mcp.json / .claudeignore typechange (` T`) — mux replaces these
#      tracked files with symlinks to the main repo. A genuinely MODIFIED
#      tracked .mcp.json (` M`) is real work and counts as dirty (the old
#      cleanup-hook regex matched any line containing `.mcp.json`, which let
#      a worktree with a real .mcp.json edit be silently deleted).
#
#   3. Untracked `node_modules` SYMLINK churn — mux symlinks node_modules
#      from the main checkout into each worktree (MCP servers need it). The
#      project's `.gitignore` typically reads `node_modules/` (trailing
#      slash), which matches only DIRECTORIES — a symlink shows up as
#      `?? node_modules` and made every mux-created worktree permanently
#      dirty, so auto-cleanup never fired (found live 2026-06-11, QA pass).
#      Excluding any untracked node_modules entry is safe: its contents are
#      never project record, so there is no work to lose.
#
#   4. Lockfile MODIFICATION — package-lock.json (and yarn/pnpm/bun lockfiles)
#      show modified in worktrees because npm rewrites `file:` dependency
#      paths to the worktree's directory depth (memory:
#      lesson_worktree_lockfile_false_dirty). Only modified-in-place lockfile
#      lines are excluded; added/deleted/renamed lockfiles count as dirty.
#      TRADEOFF (documented, accepted): an intentional, uncommitted,
#      lockfile-ONLY edit is mechanically indistinguishable from this churn
#      and classifies as clean (deletable). In practice intentional dependency
#      changes also touch package.json (which counts as dirty); without this
#      exclusion every npm-touching worktree is immortal.
#
#   5. UNTRACKED identity symlinks (`?? .mcp.json`, `?? .claudeignore`,
#      `?? pib.db`) — in a project that doesn't track these files, the mux
#      identity symlink shows as untracked instead of a typechange
#      (act:c008862c). Same manufactured churn, same exclusion — but ONLY
#      while the path is actually a symlink (checked live below): a REAL
#      user-created file at the same path (a lazily created pib.db holding
#      recorded actions, a hand-authored .mcp.json) is real work and counts
#      as dirty. A MODIFIED tracked copy (` M`) still counts as dirty,
#      exactly as in point 2.
#
#   5b. SKIP-WORKTREE'd paths are absent from porcelain BY DESIGN while
#      they are mux symlinks (worktree-session-health.sh hides the
#      typechange that way). If such a path now holds a REAL file (an
#      atomic temp+rename replaced the symlink mid-session, before any
#      health run could clear the bit), the hidden state may be a real
#      edit — counted as dirty here so a clean-verdict deletion can never
#      race the health heal (fail-DIRTY).
#
#   6. GENERATED STATE inside otherwise-authored .claude/ dirs — machine-
#      written runtime state (advisories-state.json, checklist-stats.json,
#      .claude/verification/) lives under top-level entries that also hold
#      tracked files, so the authored re-count below would claim it as real
#      work and a fully-merged worktree read "MERGE OR LOSE" (act:c008862c,
#      live specimen 2026-07-12). Untracked generated state is excluded from
#      the authored re-count; a TRACKED-and-modified copy still counts as
#      dirty (fail-safe — untracking live consumers is operator-gated).
#      The names must stay in step with watchtower-lib.mjs
#      (authoredClaudeDirs / claudeChurnIsDisposable consumers) and the
#      exclude block in worktree-session-health.sh — the noise-immunity
#      program's merge tail diffs these lists (two implementations, one
#      concept).
#
# JS-SIDE PARALLEL: the watchtower ring scripts (.mjs) carry their own
# porcelain dirty checks with their own exclusion sets. They are a parallel
# implementation owned by a separate plan and intentionally NOT consolidated
# here yet. When the JS side converges, this header is the canonical
# exclusion contract to cite.
#
# Matching is regex against whole porcelain lines — never positional column
# slicing (memory: lesson_worktree_dirty_detection_artifacts).
# -----------------------------------------------------------------------------

set -uo pipefail  # deliberately NOT -e: every failure degrades to fail-DIRTY

wt_path="${1:-}"
proj_path="${2:-}"
if [[ -z "$wt_path" || -z "$proj_path" ]]; then
  echo "usage: worktree-dirty-check.sh <wt_path> <proj_path>" >&2
  exit 2
fi

# Known CC-infrastructure churn (see EXCLUSION CONTRACT above).
INFRA_CHURN_RE='^\?\? \.claude/?$|^\?\? \.claude/|^.T \.mcp\.json$|^.T \.claudeignore$|^\?\? node_modules/?$|^[M ][M ] (.*/)?(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb)$'
# Point 5: untracked identity names are churn ONLY while the path is a live
# symlink — a real file there is real work (fail-DIRTY when in doubt).
for _f in .mcp.json .claudeignore pib.db; do
  if [[ -n "$wt_path" && -L "$wt_path/$_f" ]]; then
    INFRA_CHURN_RE="${INFRA_CHURN_RE}|^\?\? ${_f//./\\.}\$"
  fi
done
# Machine-written generated state (EXCLUSION CONTRACT point 6) — excluded
# from BOTH counting passes (non-churn and the authored re-count); keep in
# step with watchtower-lib.mjs GENERATED_STATE_PATTERNS and
# worktree-session-health.sh (merge-tail list diff; drift test in
# worktree-status-clean.test.mjs). e2e/.verify-progress.jsonl sits outside
# .claude/, so the blanket untracked-.claude churn rule never covers it —
# it must be excluded here or a /verify-touched worktree is immortal.
GENERATED_STATE_RE='^\?\? (\.claude/(cabinet/(advisories-state|checklist-stats)\.json|verification/)|e2e/\.verify-progress\.jsonl$)'
# Authored records re-included after the untracked-.claude exclusion
# (ERE has no negative lookahead, so this is a second counting pass).
# Any top-level .claude/ entry holding tracked files is authored; the static
# plans/methodology pair is the fallback floor when the index can't be read.
AUTHORED_RECORD_RE='^\?\? \.claude/(plans|methodology)/'
if [[ -n "$wt_path" ]] && authored_dirs=$(git -C "$wt_path" ls-files '.claude/' 2>/dev/null \
    | cut -d/ -f2 | sort -u | paste -sd'|' -) && [[ -n "$authored_dirs" ]]; then
  AUTHORED_RECORD_RE="^\\?\\? \\.claude/(${authored_dirs})(/|\$)"
fi

commits="?"
uncommitted="?"

if [[ -d "$wt_path" ]] && git -C "$wt_path" rev-parse --git-dir >/dev/null 2>&1; then
  main_head=$(git -C "$proj_path" rev-parse HEAD 2>/dev/null) || main_head=""
  if [[ -n "$main_head" ]]; then
    base=$(git -C "$wt_path" merge-base HEAD "$main_head" 2>/dev/null) || base=""
    if [[ -n "$base" ]]; then
      c=$(git -C "$wt_path" rev-list --count "${base}..HEAD" 2>/dev/null) && commits="$c"
    fi
  fi
  # --untracked-files=all: without it, a fully-untracked .claude/ collapses
  # to a single '?? .claude/' line, hiding any authored .claude/plans/ or
  # .claude/methodology/ doc inside it from AUTHORED_RECORD_RE — a brand-new
  # uncommitted design record would be invisible and the worktree deletable.
  if porcelain=$(git -C "$wt_path" status --porcelain --untracked-files=all 2>/dev/null); then
    if [[ -z "$porcelain" ]]; then
      uncommitted=0
    else
      non_churn=$(grep -vE "$INFRA_CHURN_RE" <<<"$porcelain" | grep -cvE "$GENERATED_STATE_RE") || true
      authored=$(grep -E "$AUTHORED_RECORD_RE" <<<"$porcelain" | grep -cvE "$GENERATED_STATE_RE") || true
      uncommitted=$(( ${non_churn:-0} + ${authored:-0} ))
    fi
    # Point 5b: skip-worktree'd paths never reach porcelain — count any
    # whose worktree path is NOT currently a symlink (a real file may be
    # hiding behind the bit; the health heal unhides it, but a deletion
    # must never race that heal).
    sw_real=0
    while IFS= read -r sw_line; do
      sw_file="${sw_line#S }"
      [[ -n "$sw_file" && ! -L "$wt_path/$sw_file" ]] && sw_real=$((sw_real+1))
    done < <(git -C "$wt_path" ls-files -v 2>/dev/null | grep '^S ' || true)
    # Point 5c: the UNTRACKED twin of 5b — a real file at an identity path
    # that porcelain can't see because a stale managed-exclude line (written
    # while the path was still a symlink) hides it until the next health
    # rebuild. Real file + untracked + absent from porcelain = hidden work.
    for _f in .mcp.json .claudeignore pib.db; do
      if [[ -e "$wt_path/$_f" && ! -L "$wt_path/$_f" ]] \
        && ! git -C "$wt_path" ls-files --error-unmatch "$_f" >/dev/null 2>&1 \
        && ! grep -qE "^.. ${_f//./\\.}\$" <<<"$porcelain"; then
        sw_real=$((sw_real+1))
      fi
    done
    if [[ "$sw_real" -gt 0 ]]; then
      uncommitted=$(( ${uncommitted:-0} + sw_real ))
    fi
  fi
fi

verdict="dirty"
[[ "$commits" == "0" && "$uncommitted" == "0" ]] && verdict="clean"

printf 'commits=%s uncommitted=%s verdict=%s\n' "$commits" "$uncommitted" "$verdict"
exit 0
