#!/usr/bin/env sh

# Names archive candidates after a pull merges work in.
#
# Every step before the merge fires from a chain and the archive fires when a
# person remembers, so shipped tasks accumulate on a board that reads as ready
# to hand a worker. This is the only event that lands after a merge.
#
# Candidates rather than closed tasks, because an all-`[x]` board entry does not
# mean the work merged. `claude-docs` marks outcomes on the branch as step 1 of
# the ship chain, so a task can read closed while its pull request is still open
# or already abandoned. The board is gitignored and an archived task has nothing
# to recover it, so `claude-tasks` confirms the work is on `main` before moving
# anything and this output says so rather than implying the check is done.
#
# It announces and never moves a file. The board is gitignored, so a shell-side
# archive leaves no diff to review with nobody watching, and `index.md` is
# regenerated by a session-scoped hook that a `mv` from a shell never fires.
#
# Husky runs this as `sh -e`, so the shebang is advisory and any bare command
# returning non-zero aborts the hook and prints a husky failure. Keep every
# test inside an `if` condition, which errexit exempts.

root=$(git worktree list --porcelain 2>/dev/null | grep -m 1 '^worktree ' | cut -d' ' -f2-) || root=''
[ -n "$root" ] || exit 0

# The board is shared scratch at the main worktree root, and `git worktree
# list` puts that root first. A pull inside a linked worktree fires this same
# hook, so trusting the working directory would read a board that is not there.
board="$root/.claude/tasks"
[ -d "$board" ] || exit 0

closed=""
count=0

for file in "$board"/*.md; do
  [ -f "$file" ] || continue

  case "$file" in
  */index.md | */priority.md) continue ;;
  esac

  # Gate on the same condition both archive verbs gate on: at least one closed
  # outcome and none open. A file carrying no outcomes at all falls out here,
  # which is what keeps notes on the board from being announced as tasks.
  if grep -q '^- \[ \]' "$file"; then
    continue
  fi

  if grep -q '^- \[x\]' "$file"; then
    closed="$closed  $(basename "$file" .md)
"
    count=$((count + 1))
  fi
done

[ "$count" -gt 0 ] || exit 0

printf '\n📋 %s archive candidate(s) on the board:\n%s\n' "$count" "$closed"
printf 'Outcomes are marked on the branch, so each still needs its work confirmed\n'
printf 'on main. Run /claude-tasks, which checks that and sweeps the plan first.\n\n'
