flurdy/agent-skills / skills/handoffs
handoffs
VerifiedBrowse and load current-repo or workspace-member handoffs, including pruned worktrees. Optional confirmed archiving and checkout recovery; loading alone never executes the saved task.
| File | Kind | Size |
|---|---|---|
| REFERENCE.md | markdown | 45.5 KB |
| SKILL.md | skill md | 36.3 KB |
| scripts/archive.shexecutable | script | 3.4 KB |
| scripts/list.shexecutable | script | 59.6 KB |
| scripts/retention.py | script | 5.0 KB |
| tests/test_list.py | script | 51.7 KB |
| tests/test_retention.py | script | 6.6 KB |
scripts/list.sh
View on GitHub#!/usr/bin/env bash
# List shared handoff files (~/.agents/handoffs/*.md) with metadata. The retired
# ~/.claude/handoffs location is listed read-only too; every row names its source
# and exact path. Sections delimited by `---<NAME>---` markers. Companion to the
# wrap-up skill. Exit 3 means the inventory is partial (see ---SOURCES---).
#
# Usage: list.sh [--recent-days N] [--retention-days N] [--stale-days N] [--summary-only] [--bead ID] [--ticket KEY]
# --recent-days N override the "recent" window (default: 3, with Mon=3, Tue=4
# weekend buffer to mirror gh-pr-list-closed.sh)
# --retention-days N retain context after handoff/completion (default: 14 days)
# --stale-days N age floor for assisted review of otherwise unclassifiable
# handoffs (default/minimum: retention window; never auto-archives)
# --summary-only suppress per-file lines in the HANDOFFS section (landscape's
# footer only needs the SUMMARY counts)
# --bead ID emit a `---MATCHED-HANDOFFS---` section: current-repo, active
# --ticket KEY handoffs whose `**Beads:**` / `**Jira:**` header field contains
# an exact ID/KEY token. Lets /next and /start-ticket surface
# "you have a handoff for this" at bead/ticket resume — without
# re-implementing repo-matching or liveness. Active excludes
# superseded and completed/stale rows even when recent retention
# clears archive-class so those rows stay in the picker.
# Pair with --check-branches for full staleness (merged-PR) filtering;
# without it only supersede filtering applies. Leaves every other
# section byte-identical, so existing callers are unaffected.
set -uo pipefail
RETENTION_HELPER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/retention.py"
if ! python3 -c 'import sys; sys.exit(sys.version_info < (3, 10))' 2>/dev/null \
|| [ ! -r "$RETENTION_HELPER" ]; then
echo "ERROR: handoff retention requires Python 3.10+ and retention.py" >&2
exit 2
fi
retention() { python3 "$RETENTION_HELPER" "$@"; }
# Records are pipe-delimited and REFERENCE.md has the model read them by field
# position, so a literal `|` in free text (a path, branch, slug or header field)
# would shift every later field and change what the picker believes a row says.
# Join through here: the delimiter and record separator are replaced with spaces
# so field positions always survive, at the cost of altering rare display text.
emit_record() {
local out="" field
for field in "$@"; do
field=${field//|/ }
field=${field//$'\n'/ }
field=${field//$'\r'/ }
out="${out}|${field}"
done
printf '%s\n' "${out#|}"
}
HANDOFFS_DIR="${HOME}/.agents/handoffs"
LEGACY_HANDOFFS_DIR="${HOME}/.claude/handoffs"
# Read compatibility across the storage move: the canonical location and the
# retired ~/.claude/handoffs are both listed, every row carrying its source and
# exact path, so existing context stays discoverable before migration. Only
# canonical-only storage is writable: wrap-up's save helper and archive.sh keep
# refusing while the legacy location exists. A location that is a symlink, not
# a directory, or unreadable is never followed or read; the inventory is then
# `partial` (exit 3) rather than looking empty.
source_status() {
if [ -L "$1" ]; then echo unsafe
elif [ ! -e "$1" ]; then echo absent
elif [ ! -d "$1" ]; then echo unsafe
elif [ ! -r "$1" ] || [ ! -x "$1" ]; then echo unreadable
else echo ok
fi
}
# Snapshot each readable location's handoff files as `name<TAB>source<TAB>path`.
# A name that cannot be represented in a record is skipped and makes the
# inventory partial instead of silently corrupting field positions.
ENTRY_LINES=()
UNLISTABLE=0
collect_source() {
local file name
for file in "$2"/*.md; do
[ -e "$file" ] || [ -L "$file" ] || continue
name=${file##*/}
case "$name" in
*'|'*|*$'\t'*|*$'\n'*|*$'\r'*) UNLISTABLE=$((UNLISTABLE+1)); continue ;;
esac
ENTRY_LINES+=("${name}"$'\t'"$1"$'\t'"${file}")
done
}
# Sets SNAPSHOT_STATUS and records one `---SOURCES---` line for the location.
snapshot_source() {
local label="$1" dir="$2" before=${#ENTRY_LINES[@]}
SNAPSHOT_STATUS=$(source_status "$dir")
if [ "$SNAPSHOT_STATUS" = ok ]; then
collect_source "$label" "$dir"
# Re-check after globbing: a location that vanished mid-read is partial.
[ "$(source_status "$dir")" = ok ] || SNAPSHOT_STATUS=vanished
fi
SOURCE_LINES+=("${label}|${dir}|${SNAPSHOT_STATUS}|$(( ${#ENTRY_LINES[@]} - before ))")
}
SOURCE_LINES=()
snapshot_source canonical "$HANDOFFS_DIR"
CANONICAL_STATUS=$SNAPSHOT_STATUS
snapshot_source legacy "$LEGACY_HANDOFFS_DIR"
LEGACY_STATUS=$SNAPSHOT_STATUS
case "${CANONICAL_STATUS}:${LEGACY_STATUS}:${UNLISTABLE}" in
ok:ok:0) STORAGE_STATUS="mixed" ;;
absent:ok:0) STORAGE_STATUS="legacy" ;;
ok:absent:0|absent:absent:0) STORAGE_STATUS="canonical" ;;
*) STORAGE_STATUS="partial" ;;
esac
case "$STORAGE_STATUS" in
legacy|mixed)
echo "NOTE: legacy handoff storage $LEGACY_HANDOFFS_DIR is listed read-only; saving and archiving stay disabled until it is migrated to $HANDOFFS_DIR." >&2 ;;
partial)
echo "WARNING: handoff inventory is partial (canonical=${CANONICAL_STATUS}, legacy=${LEGACY_STATUS}, unlistable names=${UNLISTABLE}); unsafe or unreadable locations are never followed or read." >&2 ;;
esac
RECENT_DAYS=""
RETENTION_DAYS="14"
STALE_DAYS=""
SUMMARY_ONLY=0
CHECK_BRANCHES=0
MATCH_BEAD=""
MATCH_TICKET=""
while [ $# -gt 0 ]; do
case "$1" in
--recent-days) RECENT_DAYS="$2"; shift 2 ;;
--retention-days)
if [ $# -lt 2 ] || ! [[ "$2" =~ ^[1-9][0-9]*$ ]]; then
echo "ERROR: --retention-days must be a positive integer" >&2
exit 2
fi
RETENTION_DAYS="$2"; shift 2 ;;
--stale-days) STALE_DAYS="$2"; shift 2 ;;
--summary-only) SUMMARY_ONLY=1; shift ;;
--check-branches) CHECK_BRANCHES=1; shift ;;
--bead) MATCH_BEAD="$2"; shift 2 ;;
--ticket) MATCH_TICKET="$2"; shift 2 ;;
*) shift ;;
esac
done
# A filter is active when either ID was supplied — gates the (otherwise skipped)
# per-file Beads/Jira grep and the MATCHED-HANDOFFS section.
MATCH_FILTER=""
[ -n "$MATCH_BEAD" ] || [ -n "$MATCH_TICKET" ] && MATCH_FILTER=1
# True when handoff field $1 (e.g. "`bd-123`, `bd-124`") contains the exact
# token $2. Backticks and commas are flattened to spaces, then each token is
# compared case-insensitively for an EXACT match — so `bd-12` never matches
# `bd-123`, and `AB-649` matches regardless of case drift from a branch name.
field_has_token() {
local field id tok
field=$(printf '%s' "$1" | tr '`,' ' ' | tr '[:upper:]' '[:lower:]')
id=$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]')
[ -n "$id" ] || return 1
for tok in $field; do
[ "$tok" = "$id" ] && return 0
done
return 1
}
TODAY="${HANDOFFS_TODAY:-$(date -u +%Y-%m-%d)}"
DOW=$(date -d "$TODAY" +%u 2>/dev/null \
|| date -j -f "%Y-%m-%d" "$TODAY" +%u 2>/dev/null)
if [ -z "$RECENT_DAYS" ]; then
case "$DOW" in
1) RECENT_DAYS=3 ;; # Mon → covers Fri+weekend
2) RECENT_DAYS=4 ;; # Tue → covers Fri+weekend+Mon
*) RECENT_DAYS=3 ;;
esac
fi
if ! [[ "$RECENT_DAYS" =~ ^[1-9][0-9]*$ ]]; then
echo "ERROR: --recent-days must be a positive integer" >&2
exit 2
fi
[ -n "$STALE_DAYS" ] || STALE_DAYS="$RETENTION_DAYS"
if ! [[ "$STALE_DAYS" =~ ^[1-9][0-9]*$ ]]; then
echo "ERROR: --stale-days must be a positive integer" >&2
exit 2
fi
if (( 10#$STALE_DAYS < 10#$RETENTION_DAYS )); then
STALE_DAYS="$RETENTION_DAYS"
fi
# Check whether any sibling of $1 has a *bare* `.claude` symlink pointing at
# $1 (i.e. target == $1, not target == $1/.claude/...). Print the sibling's
# path if so. Used so the "scratch" side of a bare-link pair defers to the
# "real" side (the one with the symlink).
check_bare_symlink_alias() {
local target_repo_root="$1"
local parent_dir
parent_dir=$(dirname "$target_repo_root")
[ -d "$parent_dir" ] || return 1
local sibling claude_path link_target
for sibling in "$parent_dir"/*; do
[ -d "$sibling" ] || continue
[ "$sibling" = "$target_repo_root" ] && continue
claude_path="$sibling/.claude"
[ -L "$claude_path" ] || continue
link_target=$(readlink -f "$claude_path" 2>/dev/null)
[ "$link_target" = "$target_repo_root" ] || continue
echo "$sibling"
return 0
done
return 1
}
# Resolve a directory (or one of its ancestors) to a repo identity + display.
# Output format: `{repo-id}|{repo-display}` on one line, or non-zero exit if
# we can't resolve to a git repo.
#
# - Walks up from $1 if the path itself doesn't exist (pruned worktrees still
# point at a real parent repo).
# - Identity prefers `remote.origin.url` so independent clones of the same
# upstream collapse to one row. Falls back to realpath of git-common-dir.
# - `.claude`-symlink unification has two flavours:
# • **non-bare** (target is a subdir like `B/.claude` of another repo) —
# the current side defers to the linked repo's identity.
# • **bare** (target IS another repo's root) — the current side is the
# "real" repo; the target is a scratch state-holder. Source keeps its
# identity. When the scratch side resolves on its own, a sibling scan
# finds the bare link pointing at it and defers up to the source.
# - Display is the basename of the repo root on disk, stripped of `.git`.
#
# Second argument `follow_claude_link` defaults to 1; recursive calls use 0
# so we follow at most one hop and don't cycle.
resolve_repo_info() {
local dir="${1:-.}"
local follow_claude_link="${2:-1}"
# Refuse relative paths — they would falsely match the script's pwd after
# enough `dirname`s and report a wrong repo.
[ "$dir" = "." ] || [[ "$dir" == /* ]] || return 1
local probe="$dir"
while [ -n "$probe" ] && [ "$probe" != "/" ] && [ ! -d "$probe" ]; do
probe=$(dirname "$probe")
done
[ -d "$probe" ] || return 1
local raw abs_git_dir origin repo_id repo_root repo_display
raw=$(cd "$probe" 2>/dev/null && git rev-parse --git-common-dir 2>/dev/null) || return 1
[ -n "$raw" ] || return 1
abs_git_dir=$(cd "$probe" && realpath "$raw" 2>/dev/null) || return 1
[ -n "$abs_git_dir" ] || return 1
repo_root=$(dirname "$abs_git_dir")
if [ "$follow_claude_link" -eq 1 ]; then
# Non-bare symlink: this repo's .claude → another repo's subdir →
# defer to that repo's identity.
if [ -L "$repo_root/.claude" ]; then
local link_target linked_root
link_target=$(readlink -f "$repo_root/.claude" 2>/dev/null)
if [ -n "$link_target" ] && [ -d "$link_target" ]; then
linked_root=$(cd "$link_target" 2>/dev/null && git rev-parse --show-toplevel 2>/dev/null)
if [ -n "$linked_root" ]; then
linked_root=$(realpath "$linked_root" 2>/dev/null)
if [ -n "$linked_root" ] \
&& [ "$linked_root" != "$repo_root" ] \
&& [ "$link_target" != "$linked_root" ]; then
# Non-bare: defer
resolve_repo_info "$linked_root" 0
return $?
fi
# Otherwise it's bare — fall through to normal resolution
# so the source side keeps its own identity.
fi
fi
fi
# Inverse: if a sibling has a bare `.claude` symlink pointing at this
# repo, this is the scratch side — defer to the sibling's identity.
local alias_root
alias_root=$(check_bare_symlink_alias "$repo_root" 2>/dev/null || true)
if [ -n "$alias_root" ]; then
resolve_repo_info "$alias_root" 0
return $?
fi
fi
origin=$(cd "$probe" 2>/dev/null && git config --get remote.origin.url 2>/dev/null || true)
if [ -n "$origin" ]; then
repo_id="$origin"
else
repo_id="$abs_git_dir"
fi
repo_display=$(basename "$repo_root")
repo_display="${repo_display%.git}"
emit_record "${repo_id}" "${repo_display}"
}
# Plain-directory identity for paths outside any git repo (a workspace root
# such as ~/Code/flurdy). Keyed `dir:{realpath}` so it can never collide with a
# repo key; only an existing directory qualifies — a pruned path stays
# UNRESOLVED rather than silently keying to whatever parent survives.
resolve_dir_info() {
local dir="$1" real
[[ "$dir" == /* ]] || return 1
[ -d "$dir" ] || return 1
real=$(realpath "$dir" 2>/dev/null) || return 1
[ -n "$real" ] || return 1
emit_record "dir:${real}" "$(basename "$real")"
}
# Current identity: the enclosing repo, else the directory itself (`dir:` key),
# else `NONE|NONE`. CURRENT_IS_REPO gates everything that needs git.
CURRENT_IS_REPO=0
CURRENT_KIND="NONE"
CURRENT_INFO=$(resolve_repo_info . 2>/dev/null || true)
if [ -n "$CURRENT_INFO" ]; then
CURRENT_IS_REPO=1
CURRENT_KIND="repo"
else
CURRENT_INFO=$(resolve_dir_info "$PWD" 2>/dev/null || true)
[ -n "$CURRENT_INFO" ] && CURRENT_KIND="dir"
fi
if [ -n "$CURRENT_INFO" ]; then
CURRENT_REPO_KEY="${CURRENT_INFO%%|*}"
CURRENT_REPO_DISPLAY="${CURRENT_INFO##*|}"
else
CURRENT_REPO_KEY="NONE"
CURRENT_REPO_DISPLAY="NONE"
fi
date_days_ago() {
local days="$1"
date -I -d "$TODAY - ${days} days" 2>/dev/null \
|| date -j -f "%Y-%m-%d" "-v-${days}d" "$TODAY" +%Y-%m-%d 2>/dev/null
}
CUTOFF=$(date_days_ago "$RECENT_DAYS")
AGE_REVIEW_CUTOFF=$(date_days_ago "$STALE_DAYS")
if [ -z "$CUTOFF" ] || [ -z "$AGE_REVIEW_CUTOFF" ]; then
echo "ERROR: unable to calculate handoff age cutoffs" >&2
exit 2
fi
# --- Branch-liveness setup (only with --check-branches, only in a repo) -----
# Each classified repo gets one `git ls-remote` (network, timeout-guarded) for
# remote existence; merged/ancestor checks are local against that repo's default
# branch tip. The current repo is set up first and workspace members are repointed
# through setup_liveness below. Degrades gracefully when offline.
TIMEOUT=""
if command -v timeout >/dev/null 2>&1; then TIMEOUT="timeout 8"
elif command -v gtimeout >/dev/null 2>&1; then TIMEOUT="gtimeout 8"; fi
# Repo scope for every liveness query. "." is the invocation pwd (the current
# repo). The workspace-member pass repoints this so branch/PR/bead lookups run
# inside the member repo — running them in pwd is exactly why member rows used
# to report `unknown` for everything.
LIVENESS_DIR="."
lgit() { git -C "$LIVENESS_DIR" "$@"; }
compute_default_branch_name() {
local dref cand
dref=$(lgit symbolic-ref --quiet refs/remotes/origin/HEAD 2>/dev/null || true)
if [ -n "$dref" ]; then
echo "${dref##*/}"; return
fi
for cand in main master; do
if lgit rev-parse --verify --quiet "$cand" >/dev/null 2>&1 \
|| lgit rev-parse --verify --quiet "origin/$cand" >/dev/null 2>&1; then
echo "$cand"; return
fi
done
}
# Short name of the default branch. Computed whenever we're in a repo (not just
# under --check-branches) because the supersede pass — which runs for every
# caller, including wrap-up's no-flag invocation — needs it too: two handoffs
# co-resident on the trunk are NOT the same thread (see is_trunk_branch).
DEFAULT_BRANCH_NAME=""
if [ "$CURRENT_IS_REPO" -eq 1 ]; then
DEFAULT_BRANCH_NAME=$(compute_default_branch_name)
fi
DEFAULT_TIP=""
REMOTE_HEADS=""
REMOTE_OK=0
# Point every liveness global at $1 and re-run the probes there. Called once for
# the current repo, then once per workspace member that owns handoffs. PR_LINES
# is filled here too (see the PR-liveness note below) because `gh` resolves its
# repo from cwd, so it must be re-run per member rather than reused.
setup_liveness() {
LIVENESS_DIR="${1:-.}"
DEFAULT_BRANCH_NAME=$(compute_default_branch_name)
DEFAULT_TIP=""; REMOTE_HEADS=""; REMOTE_OK=0; PR_LINES=""; PR_OK=0
local dref cand
dref=$(lgit symbolic-ref --quiet refs/remotes/origin/HEAD 2>/dev/null || true)
if [ -n "$dref" ]; then
DEFAULT_TIP="${dref#refs/remotes/}"
else
for cand in origin/main origin/master main master; do
if lgit rev-parse --verify --quiet "$cand" >/dev/null 2>&1; then
DEFAULT_TIP="$cand"; break
fi
done
fi
if REMOTE_HEADS=$($TIMEOUT git -C "$LIVENESS_DIR" ls-remote --heads origin 2>/dev/null); then
REMOTE_OK=1
fi
if command -v gh >/dev/null 2>&1; then
if PR_LINES=$(cd "$LIVENESS_DIR" 2>/dev/null && $TIMEOUT gh pr list --state all --limit 200 \
--json number,state,headRefName,url,mergedAt,closedAt \
--jq '.[] | [.headRefName, (.state|ascii_downcase), (.number|tostring), .url, ((if .state == "MERGED" then .mergedAt else .closedAt end) // "-")] | @tsv' \
2>/dev/null); then
PR_OK=1
fi
fi
}
# True when $1 is a trunk branch — the repo's default branch, or the universal
# main/master. The trunk is never a meaningful "same thread" or "merged feature"
# signal: a worktree sitting on main while the real work lives on a feature
# branch is the trunk-parking case. Used to suppress the `branch` supersede
# reason and the `merged` branch-state. Same-slug / same-day-collision
# supersedes still apply on the trunk — only branch co-residence is discounted.
is_trunk_branch() {
local b="$1"
[ -z "$b" ] && return 1
[ "$b" = "?" ] && return 1
case "$b" in main|master) return 0 ;; esac
[ -n "$DEFAULT_BRANCH_NAME" ] && [ "$b" = "$DEFAULT_BRANCH_NAME" ] && return 0
return 1
}
# --- PR-liveness setup (auto-enabled when `gh` exists; no separate flag) ------
# Tied to --check-branches (the only "network detail wanted" caller) so that
# landscape's --summary-only and wrap-up's plain calls stay network-free. One
# batched `gh pr list` (timeout-guarded) covers every branch; we map by
# headRefName locally. `gh`'s embedded --jq means no external jq dependency.
# Degrades exactly like ls-remote: missing/unauthenticated/timed-out gh → every
# row reports pr-state `unknown` and the local heuristic stands.
PR_LINES=""
PR_OK=0
# Outside a repo there is nothing to check branches against: drop the flag so
# directory-matched rows classify as `unknown` rather than probing pwd with git.
if [ "$CHECK_BRANCHES" -eq 1 ]; then
if [ "$CURRENT_IS_REPO" -eq 1 ]; then
setup_liveness "."
else
CHECK_BRANCHES=0
fi
fi
# Look up the PR state for a handoff from the cached `gh` listing. A PR matches
# either by branch (headRefName) OR by a number recorded in the handoff's
# `**PRs:**` field ($2) — the latter is what catches the trunk-parking case,
# where wrap-up recorded `main` as the branch (the feature branch was already
# gone) but stored the real PR number in the body. Without the number fallback
# such handoffs look up `main`, match nothing, and wrongly render 🟢 live.
# Echoes `{state}|{number}|{url}|{completed-at}`; timing is empty unless every
# matching PR at the winning precedence has a valid timestamp. Open PRs win;
# otherwise merged > closed. Dates never stand in for missing completion evidence.
pr_state() {
local b="$1" prfield="${2:-}"
[ "$PR_OK" -eq 1 ] || { echo "unknown||"; return; }
local nums n
nums=$(printf '%s' "$prfield" | grep -oE '#[0-9]+' | tr -d '#')
# Nothing to match on at all (branch `?` and no recorded numbers) → unknown.
{ [ "$b" != "?" ] || [ -n "$nums" ]; } || { echo "unknown||"; return; }
local best_rank=0 best="none||"
local hb st num url completed rank match
local completed_times=()
while IFS=$'\t' read -r hb st num url completed; do
[ -n "$hb" ] || continue
match=0
[ "$b" != "?" ] && [ "$hb" = "$b" ] && match=1
if [ "$match" -eq 0 ] && [ -n "$nums" ]; then
for n in $nums; do [ "$n" = "$num" ] && { match=1; break; }; done
fi
[ "$match" -eq 1 ] || continue
case "$st" in
open) rank=3 ;;
merged) rank=2 ;;
closed) rank=1 ;;
*) rank=0 ;;
esac
if [ "$rank" -gt "$best_rank" ]; then
best_rank=$rank
best="${st}|${num}|${url}"
completed_times=()
fi
[ "$rank" -eq "$best_rank" ] && completed_times+=("$completed")
done <<< "$PR_LINES"
echo "${best}|$(retention latest -- "${completed_times[@]}")"
}
# --- Bead-closure setup (local; no network, no --check-branches needed) -------
# A finished task often leaves no live branch/PR — on a trunk-based repo there's
# no PR at all, and even on a PR repo the handoff may have recorded `main`. The
# bead it referenced is the ground-truth "done" signal in those cases. This is a
# local `bd` query, so it runs whenever beads exist (independent of the network
# --check-branches gate) — that lets landscape's offline call also stop counting
# bead-closed handoffs as live threads.
# Bead lookups are repo-scoped for the same reason liveness is: a workspace
# member keeps its own `.beads` store, and the workspace root's store (often
# deliberately empty) knows nothing about a member's beads.
BEADS_DIR="."
BEADS_AVAILABLE=""
setup_beads() {
BEADS_DIR="${1:-.}"
BEADS_AVAILABLE=""
local root
root=$(git -C "$BEADS_DIR" rev-parse --show-toplevel 2>/dev/null || true)
if command -v bd >/dev/null 2>&1 && [ -n "$root" ] && [ -d "$root/.beads" ]; then
BEADS_AVAILABLE=1
fi
}
setup_beads "."
# --- Workspace members (mgit / git submodules) --------------------------------
# A multi-repo workspace root aggregates member repos that are independent git
# repos with their own identities. Handoffs recorded inside a member therefore
# key to the member, not the root — so from the workspace root (the directory
# you actually orient in) they land in "other repos": invisible and unpickable.
# Discover the members here so their handoffs can be surfaced and classified.
# Cheap by construction: one `--members-only` call, no per-member status sweep.
WS_KEYS=()
WS_DISPLAYS=()
WS_PATHS=()
if [ "$CURRENT_IS_REPO" -eq 1 ]; then
MR_SCRIPT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../wrap-up/scripts" 2>/dev/null && pwd)/multirepo.sh"
if [ -x "$MR_SCRIPT" ]; then
ws_root=""
ws_section=""
while IFS= read -r line; do
case "$line" in
---ROOT---) ws_section="root"; continue ;;
---REPOS---) ws_section="repos"; continue ;;
---*---) ws_section=""; continue ;;
esac
case "$ws_section" in
root) ws_root="$line"; ws_section="" ;;
repos)
[ -n "$ws_root" ] || continue
m_path=$(readlink -f "$ws_root/$line" 2>/dev/null) || continue
{ [ -n "$m_path" ] && [ -d "$m_path" ]; } || continue
m_info=$(resolve_repo_info "$m_path") || continue
m_key="${m_info%%|*}"
# The root repo is itself a member ("."). It's already the
# current repo, so skip it rather than double-listing.
[ "$m_key" = "$CURRENT_REPO_KEY" ] && continue
WS_KEYS+=("$m_key")
WS_DISPLAYS+=("${m_info##*|}")
WS_PATHS+=("$m_path")
;;
esac
done < <("$MR_SCRIPT" --members-only 2>/dev/null)
fi
fi
# Index of the workspace member owning repo-key $1, or non-zero if none.
ws_index_for_key() {
local k="$1" wi
for wi in "${!WS_KEYS[@]}"; do
[ "${WS_KEYS[$wi]}" = "$k" ] && { echo "$wi"; return 0; }
done
return 1
}
# Echo "{closed} {total} {latest-closed-at}" for the beads named in field $1 (backtick/comma
# flattened, filtered to `{prefix}-{suffix}` shapes — bd-123, ab-1505,
# myrepo-lf9d). "0 0" when beads are unavailable, the field is empty, the
# field is truncated with "(+N more)" (can't verify all — conservative), or no
# token resolves in the db. One batched, local `bd list --id` per call (no
# network). The caller decides done-ness: all-closed = (total>0 && closed==total).
beads_counts() {
local field="$1"
[ -n "$BEADS_AVAILABLE" ] || { echo "0 0"; return; }
[ -n "$field" ] || { echo "0 0"; return; }
case "$field" in *"more)"*) echo "0 0"; return ;; esac
local ids="" tok
for tok in $(printf '%s' "$field" | tr '`,' ' '); do
case "$tok" in
[A-Za-z]*-[A-Za-z0-9]*) ids="${ids:+$ids,}$tok" ;;
esac
done
[ -n "$ids" ] || { echo "0 0"; return; }
local json
json=$(bd -C "$BEADS_DIR" --readonly list --id "$ids" --all --json --limit 0 --no-pager 2>/dev/null) || return 1
retention beads --ids "$ids" <<< "$json"
}
# Classify one branch as live / merged / gone / unknown. `unknown` means we
# couldn't determine it (no --check-branches, branch is `?`, or offline with no
# local ref). Only `merged` and `gone` count as stale.
branch_state() {
local b="$1"
[ "$b" = "?" ] && { echo "unknown"; return; }
# The trunk is never "merged" in the feature sense — its tip is trivially an
# ancestor of DEFAULT_TIP, so the merge-base check below would always fire. A
# handoff recorded on the trunk (wrap-up captured a worktree sitting on main
# while the real work lived on a feature branch elsewhere) tells us nothing
# about liveness — report `unknown` so it renders 🟢 live and never becomes a
# stale/archive candidate. PR detection still applies separately.
if is_trunk_branch "$b"; then
echo "unknown"; return
fi
local local_exists=0 remote_sha="" test_commit=""
if lgit show-ref --verify --quiet "refs/heads/$b" 2>/dev/null; then
local_exists=1
test_commit="refs/heads/$b"
fi
if [ "$REMOTE_OK" -eq 1 ]; then
remote_sha=$(printf '%s\n' "$REMOTE_HEADS" | awk -v r="refs/heads/$b" '$2==r {print $1}')
[ -z "$test_commit" ] && [ -n "$remote_sha" ] && test_commit="$remote_sha"
fi
if [ -n "$test_commit" ] && [ -n "$DEFAULT_TIP" ] \
&& lgit merge-base --is-ancestor "$test_commit" "$DEFAULT_TIP" 2>/dev/null; then
echo "merged"; return
fi
if [ "$local_exists" -eq 0 ] && [ "$REMOTE_OK" -eq 1 ] && [ -z "$remote_sha" ]; then
echo "gone"; return
fi
if [ "$local_exists" -eq 0 ] && [ "$REMOTE_OK" -eq 0 ]; then
echo "unknown"; return
fi
echo "live"
}
echo "---CURRENT-REPO---"
echo "$CURRENT_REPO_KEY"
echo "---CURRENT-REPO-DISPLAY---"
echo "$CURRENT_REPO_DISPLAY"
echo "---CURRENT-REPO-KIND---"
echo "$CURRENT_KIND"
echo "---RECENT-WINDOW-DAYS---"
echo "$RECENT_DAYS"
echo "---RETENTION-DAYS---"
echo "$RETENTION_DAYS"
echo "---AS-OF-DATE---"
echo "$TODAY"
echo "---STALE-DAYS---"
echo "$STALE_DAYS"
echo "---HANDOFFS-DIR---"
echo "$HANDOFFS_DIR"
echo "---STORAGE---"
echo "$STORAGE_STATUS"
# `{source}|{dir}|{status}|{listed}` per location; status is ok, absent, unsafe,
# unreadable or vanished.
echo "---SOURCES---"
for line in "${SOURCE_LINES[@]}"; do
echo "$line"
done
echo "---CUTOFF---"
echo "$CUTOFF"
TOTAL=0
CUR_TOTAL=0
CUR_RECENT=0
CUR_PRUNED=0
CUR_SUPERSEDED=0
PRUNED_TOTAL=0
SUPERSEDED_TOTAL=0
UNRESOLVED_COUNT=0
# Parallel arrays for per-repo aggregation (bash 3.2 compatible — macOS).
OTHER_KEYS=()
OTHER_DISPLAYS=()
OTHER_COUNTS=()
# Parallel arrays buffering every handoff record. Supersede classification
# needs all records before any line is emitted, so we collect first, compute
# supersede in a second pass, then print.
R_FILE=()
R_DATE=()
R_TIME=() # HH:MM from the handoff's "# Resume:" header, falling back to file mtime
R_HAS_HEADER_TIME=()
R_SLUG=()
R_BASESLUG=() # slug with a trailing collision suffix (-2, -3, …) removed
R_SUFFIX=() # the stripped collision suffix, or empty
R_CWD=()
R_BRANCH=()
R_REPO=()
R_EXISTS=()
R_BEADS=() # raw `**Beads:**` field content (parsed under --bead/--ticket or when beads exist)
R_DELIV=() # raw `**Deliverable:**` field content — own-work beads (wrap-up v0.10.0+); keys beads-done when present
R_JIRA=() # raw `**Jira:**` field content (parsed under --bead/--ticket or --check-branches)
R_PRS=() # raw `**PRs:**` field content (parsed under --check-branches; PR-number fallback)
R_SOURCE=() # canonical | legacy — the location the file was read from
R_PATH=() # exact path of the file; consumers load this, never dir+filename
R_MATCH=() # repo | session | empty — why the row is current
LEGACY_TOTAL=0
# Same filename present in both locations: `{filename}|identical|different`.
# Such rows stay separate and never supersede each other.
COLLISION_LINES=()
bump_other() {
local key="$1" display="$2"
local i
for i in "${!OTHER_KEYS[@]}"; do
if [ "${OTHER_KEYS[$i]}" = "$key" ]; then
OTHER_COUNTS[$i]=$((OTHER_COUNTS[$i]+1))
return
fi
done
OTHER_KEYS+=("$key")
OTHER_DISPLAYS+=("$display")
OTHER_COUNTS+=(1)
}
if [ "${#ENTRY_LINES[@]}" -gt 0 ]; then
# Newest first by filename (handoff filenames begin with YYYY-MM-DD); for a
# name present in both locations the canonical row comes first.
while IFS=$'\t' read -r BASE SOURCE F; do
[ -f "$F" ] || continue
TOTAL=$((TOTAL+1))
[ "$SOURCE" = legacy ] && LEGACY_TOTAL=$((LEGACY_TOTAL+1))
if [[ "$BASE" =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2})-(.+)\.md$ ]]; then
DATE="${BASH_REMATCH[1]}"
SLUG="${BASH_REMATCH[2]}"
else
DATE=$(date -r "$F" +%Y-%m-%d 2>/dev/null)
SLUG="${BASE%.md}"
fi
# Time of the handoff. Prefer the HH:MM trailing the date on the
# "# Resume:" header (wrap-up v0.8.0+ embeds it — authoritative, and
# survives the file being copied/synced across machines). Fall back to
# the file's mtime so older handoffs and hand-edited ones still show a
# time. `?` only if neither is available.
TIME=$(grep -m1 '^# Resume:' "$F" 2>/dev/null \
| sed -n 's/.*[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}[[:space:]]\{1,\}\([0-2][0-9]:[0-5][0-9]\).*/\1/p')
HAS_HEADER_TIME=""
[ -n "$TIME" ] && HAS_HEADER_TIME="Y"
[ -z "$TIME" ] && TIME=$(date -r "$F" +%H:%M 2>/dev/null)
[ -z "$TIME" ] && TIME="?"
LINE=$(grep -m1 '^\*\*Where to pick up:\*\*' "$F" 2>/dev/null || true)
# Prefer "worktree at `PATH`" — that's reliably absolute. Otherwise use
# the first backtick-quoted token, which may be relative.
CWD=$(echo "$LINE" | sed -n 's/.*worktree at `\([^`]*\)`.*/\1/p')
if [ -z "$CWD" ]; then
CWD=$(echo "$LINE" | sed -n 's/.*\*\*Where to pick up:\*\* `\([^`]*\)`.*/\1/p')
fi
BRANCH=$(echo "$LINE" | sed -n 's/.*on branch `\([^`]*\)`.*/\1/p')
if [ -z "$BRANCH" ]; then
BRANCH=$(echo "$LINE" | sed -n 's/.*` on `\([^`]*\)`.*/\1/p')
fi
[ -z "$BRANCH" ] && BRANCH="?"
# `Repo root:` is the canonical repo identity (wrap-up v0.2.0+).
# Prefer it for resolution — it survives pruned worktrees and bogus
# `Where to pick up:` paths. Falls back to walking up cwd for older
# handoffs that don't have the field.
REPO_ROOT=$(grep -m1 '^\*\*Repo root:\*\*' "$F" 2>/dev/null | sed -n 's/.*\*\*Repo root:\*\* `\([^`]*\)`.*/\1/p' || true)
# Beads/Jira/PRs header fields. Parsed conditionally so the hot path
# (wrap-up's no-flag call) pays only for what it uses:
# - Beads: with a filter, local beads, or --check-branches (members may
# own stores even when the root has none).
# - Jira: when filtering, OR under --check-branches (the skill resolves
# Jira-Done for live rows from this field).
# - PRs: under --check-branches only (PR-number fallback for pr_state).
# Strip the `**Field:**` label; keep the raw token list.
BEADS_FIELD=""; DELIV_FIELD=""; JIRA_FIELD=""; PRS_FIELD=""
if [ -n "$MATCH_FILTER" ] || [ -n "$BEADS_AVAILABLE" ] || [ "$CHECK_BRANCHES" -eq 1 ]; then
BEADS_FIELD=$(grep -m1 '^\*\*Beads:\*\*' "$F" 2>/dev/null | sed 's/^\*\*Beads:\*\*[[:space:]]*//' || true)
# `**Deliverable:**` (wrap-up v0.10.0+) names just the own-work beads —
# the subset whose closure means this handoff is finished. Keys the
# bead-closure check when present, so trunk-parked handoffs whose
# **Beads:** list also carries context/epic beads still classify.
DELIV_FIELD=$(grep -m1 '^\*\*Deliverable:\*\*' "$F" 2>/dev/null | sed 's/^\*\*Deliverable:\*\*[[:space:]]*//' || true)
fi
if [ -n "$MATCH_FILTER" ] || [ "$CHECK_BRANCHES" -eq 1 ]; then
JIRA_FIELD=$(grep -m1 '^\*\*Jira:\*\*' "$F" 2>/dev/null | sed 's/^\*\*Jira:\*\*[[:space:]]*//' || true)
fi
if [ "$CHECK_BRANCHES" -eq 1 ]; then
PRS_FIELD=$(grep -m1 '^\*\*PRs:\*\*' "$F" 2>/dev/null | sed 's/^\*\*PRs:\*\*[[:space:]]*//' || true)
fi
if [ -n "$CWD" ] && [ -d "$CWD" ]; then
EXISTS="Y"
else
EXISTS="N"
fi
# Resolve repo identity. Order: Repo root field → walk-up from cwd.
REPO_KEY="UNRESOLVED"
REPO_DISPLAY=""
if [ -n "$REPO_ROOT" ]; then
INFO=$(resolve_repo_info "$REPO_ROOT" 2>/dev/null || true)
if [ -n "$INFO" ]; then
REPO_KEY="${INFO%%|*}"
REPO_DISPLAY="${INFO##*|}"
fi
fi
if [ "$REPO_KEY" = "UNRESOLVED" ] && [ -n "$CWD" ]; then
INFO=$(resolve_repo_info "$CWD" 2>/dev/null || true)
if [ -n "$INFO" ]; then
REPO_KEY="${INFO%%|*}"
REPO_DISPLAY="${INFO##*|}"
fi
fi
# No repo anywhere above it: a still-existing plain directory (e.g. a
# non-git workspace root) is its own identity, so handoffs written from
# there are pickable when /handoffs runs from that same directory.
if [ "$REPO_KEY" = "UNRESOLVED" ] && [ -n "$CWD" ]; then
INFO=$(resolve_dir_info "$CWD" 2>/dev/null || true)
if [ -n "$INFO" ]; then
REPO_KEY="${INFO%%|*}"
REPO_DISPLAY="${INFO##*|}"
fi
fi
# A trailing -N can be a same-day filename collision suffix, but it
# can also be part of a normal topic (for example, ticket-123). Keep
# it only for the exact base/suffix collision tie-breaker below; the
# header time is the normal same-day recency signal.
SUFFIX=$(printf '%s' "$SLUG" | sed -n 's/.*-\([0-9]\{1,\}\)$/\1/p')
if [ -n "$SUFFIX" ]; then
BASESLUG="${SLUG%-$SUFFIX}"
else
BASESLUG="$SLUG"
fi
R_FILE+=("$BASE")
R_DATE+=("$DATE")
R_TIME+=("$TIME")
R_HAS_HEADER_TIME+=("$HAS_HEADER_TIME")
R_SLUG+=("$SLUG")
R_BASESLUG+=("$BASESLUG")
R_SUFFIX+=("$SUFFIX")
R_CWD+=("$CWD")
R_BRANCH+=("$BRANCH")
R_REPO+=("$REPO_KEY")
R_EXISTS+=("$EXISTS")
R_BEADS+=("$BEADS_FIELD")
R_DELIV+=("$DELIV_FIELD")
R_JIRA+=("$JIRA_FIELD")
R_PRS+=("$PRS_FIELD")
R_SOURCE+=("$SOURCE")
R_PATH+=("$F")
prev=$((${#R_FILE[@]} - 2))
if [ "$prev" -ge 0 ] && [ "${R_FILE[$prev]}" = "$BASE" ]; then
if cmp -s "${R_PATH[$prev]}" "$F"; then
COLLISION_LINES+=("${BASE}|identical")
else
COLLISION_LINES+=("${BASE}|different")
fi
fi
[ "$EXISTS" = "N" ] && PRUNED_TOTAL=$((PRUNED_TOTAL+1))
[ "$REPO_KEY" = "UNRESOLVED" ] && UNRESOLVED_COUNT=$((UNRESOLVED_COUNT+1))
# Which identity makes this row current: `repo`, or `session` when the
# wrap-up ran from this directory about another repo (`Session dir:`).
# The repo key is unchanged, so liveness and supersede stay with the
# owning repo. Workspace-member rows keep their member routing, and only
# an existing session directory can match.
MATCH=""
if [ "$CURRENT_REPO_KEY" != "NONE" ]; then
if [ "$REPO_KEY" = "$CURRENT_REPO_KEY" ]; then
MATCH="repo"
elif ! ws_index_for_key "$REPO_KEY" >/dev/null; then
SESSION_DIR=$(grep -m1 '^\*\*Session dir:\*\*' "$F" 2>/dev/null | sed -n 's/.*\*\*Session dir:\*\* `\([^`]*\)`.*/\1/p' || true)
if [ -n "$SESSION_DIR" ] && [ -d "$SESSION_DIR" ]; then
INFO=$(resolve_repo_info "$SESSION_DIR" 2>/dev/null || resolve_dir_info "$SESSION_DIR" 2>/dev/null || true)
[ "${INFO%%|*}" = "$CURRENT_REPO_KEY" ] && MATCH="session"
fi
fi
fi
R_MATCH+=("$MATCH")
if [ -n "$MATCH" ]; then
CUR_TOTAL=$((CUR_TOTAL+1))
[ "$EXISTS" = "N" ] && CUR_PRUNED=$((CUR_PRUNED+1))
if [[ "$DATE" > "$CUTOFF" ]] || [ "$DATE" = "$CUTOFF" ]; then
CUR_RECENT=$((CUR_RECENT+1))
fi
elif [ "$REPO_KEY" != "UNRESOLVED" ]; then
bump_other "$REPO_KEY" "$REPO_DISPLAY"
fi
done < <(printf '%s\n' "${ENTRY_LINES[@]}" | sort -t "$(printf '\t')" -k1,1r -k2,2)
fi
# --- Supersede pass -------------------------------------------------------
# A handoff is superseded by a *newer* handoff in the SAME repo that shares its
# branch, its exact slug, or its base slug via a same-day collision suffix.
# Ticket/cwd overlap is deliberately NOT a supersede signal — a ticket spans
# many handoffs legitimately. The `branch` reason also excludes the trunk: two
# distinct threads both recorded on main (the trunk-parking case) are NOT the
# same thread, so trunk co-residence must not collapse them — they only
# supersede on an exact slug or same-day collision. For each record we keep the
# newest superseding file and the reason. UNRESOLVED records never participate,
# and the same filename in both storage locations is a copy, not a newer thread.
# Date orders records across days. On the same day, the authoritative header
# time orders records when available; unknown/equal times do not assert an
# order. The one safe tie-breaker is an established filename collision family
# (`topic`, `topic-2`, `topic-3`), because wrap-up creates those suffixes only
# after the original filename exists. A numeric topic slug alone is never a
# rank signal.
collision_base() {
local index="$1" base="${R_BASESLUG[$1]}" k=0
if [ -n "${R_SUFFIX[$index]}" ]; then
while [ "$k" -lt "$N" ]; do
if [ "${R_REPO[$k]}" = "${R_REPO[$index]}" ] \
&& [ "${R_DATE[$k]}" = "${R_DATE[$index]}" ] \
&& [ "${R_SLUG[$k]}" = "$base" ]; then
printf '%s' "$base"
return
fi
k=$((k+1))
done
return 1
fi
while [ "$k" -lt "$N" ]; do
if [ "${R_REPO[$k]}" = "${R_REPO[$index]}" ] \
&& [ "${R_DATE[$k]}" = "${R_DATE[$index]}" ] \
&& [ -n "${R_SUFFIX[$k]}" ] \
&& [ "${R_BASESLUG[$k]}" = "${R_SLUG[$index]}" ]; then
printf '%s' "${R_SLUG[$index]}"
return
fi
k=$((k+1))
done
return 1
}
record_is_newer() {
local older="$1" newer="$2" older_time="${R_TIME[$1]}" newer_time="${R_TIME[$2]}"
local older_base newer_base older_suffix newer_suffix
[[ "${R_DATE[$newer]}" > "${R_DATE[$older]}" ]] && return 0
[ "${R_DATE[$newer]}" = "${R_DATE[$older]}" ] || return 1
if [ "${R_HAS_HEADER_TIME[$older]}" = "Y" ] \
&& [ "${R_HAS_HEADER_TIME[$newer]}" = "Y" ] \
&& [[ "$older_time" =~ ^[0-2][0-9]:[0-5][0-9]$ ]] \
&& [[ "$newer_time" =~ ^[0-2][0-9]:[0-5][0-9]$ ]] \
&& [ "$older_time" != "$newer_time" ]; then
[[ "$newer_time" > "$older_time" ]]
return
fi
older_base=$(collision_base "$older" 2>/dev/null || true)
newer_base=$(collision_base "$newer" 2>/dev/null || true)
[ -n "$older_base" ] && [ "$older_base" = "$newer_base" ] || return 1
older_suffix="${R_SUFFIX[$older]:-0}"
newer_suffix="${R_SUFFIX[$newer]:-0}"
(( 10#$newer_suffix > 10#$older_suffix ))
}
R_SUPBY=()
R_SUPREASON=()
N=${#R_FILE[@]}
i=0
while [ "$i" -lt "$N" ]; do
best_idx=-1
best_reason=""
j=0
while [ "$j" -lt "$N" ]; do
if [ "$j" -ne "$i" ] \
&& [ "${R_FILE[$j]}" != "${R_FILE[$i]}" ] \
&& [ "${R_REPO[$i]}" != "UNRESOLVED" ] \
&& [ "${R_REPO[$j]}" = "${R_REPO[$i]}" ] \
&& record_is_newer "$i" "$j"; then
reason=""
if [ "${R_BRANCH[$i]}" != "?" ] && [ "${R_BRANCH[$j]}" = "${R_BRANCH[$i]}" ] \
&& ! is_trunk_branch "${R_BRANCH[$i]}"; then
reason="branch"
elif [ "${R_SLUG[$j]}" = "${R_SLUG[$i]}" ]; then
reason="slug"
elif [ -n "${R_SUFFIX[$j]}" ] \
&& [ "${R_BASESLUG[$j]}" = "${R_SLUG[$i]}" ] \
&& [ "${R_DATE[$j]}" = "${R_DATE[$i]}" ]; then
reason="collision"
fi
if [ -n "$reason" ] \
&& { [ "$best_idx" -lt 0 ] || record_is_newer "$best_idx" "$j"; }; then
best_idx="$j"
best_reason="$reason"
fi
fi
j=$((j+1))
done
if [ "$best_idx" -ge 0 ]; then
R_SUPBY+=("${R_FILE[$best_idx]}")
R_SUPREASON+=("$best_reason")
SUPERSEDED_TOTAL=$((SUPERSEDED_TOTAL+1))
# Archive counters stay repo-only: session rows are never archive candidates.
if [ "${R_MATCH[$i]}" = "repo" ]; then
CUR_SUPERSEDED=$((CUR_SUPERSEDED+1))
fi
else
R_SUPBY+=("")
R_SUPREASON+=("")
fi
i=$((i+1))
done
# --- Branch/PR-liveness pass (current + workspace; needs --check-branches) ---
# Fills R_STATE (live/merged/gone/unknown) and, when gh is available, the PR
# fields R_PRSTATE/R_PRNUM/R_PRURL. The same classifier is repointed per workspace
# member; unrelated-repo rows stay `unknown`.
#
# R_ARCHCLASS is the per-row archive recommendation used by §3b:
# safe — superseded, or an older PR/bead/branch completion signal. Low regret;
# the context lives on (newer handoff) or the work demonstrably landed.
# keep — an older closed PR or gone branch with no merged evidence. Higher
# regret; may be the only record of an abandoned thread.
# "" — live/unknown work, or a recent non-superseded row retained for context.
# Precedence before recent-retention: supersede > open PR > merged PR > beads-closed > closed PR >
# local merged > gone. A merged PR is ground truth that beats local ancestry —
# the fix for squash-merges, where the branch is never an ancestor of the
# default tip. Beads-closed ("done") is the fix for the trunk case, where there
# is no feature branch/PR to read — it ranks just under a merged PR but above a
# closed-unmerged PR (the work shipped some other way) and an open PR still wins
# (active review beats a sub-bead closing). R_BEADSDONE records the bead signal
# so the skill renders "✅ done (beads closed)". Jira-Done is resolved by the
# skill from the emitted Jira field (bash can't call the Jira MCP).
# CUR_STALE counts the §3b "stale" group: archivable for a NON-supersede reason
# (superseded rows are counted by CUR_SUPERSEDED and grouped separately).
#
# R_BEADSPROGRESS ("{closed}/{total}", or empty) and R_NEEDSREVIEW ("Y"/empty)
# support trunk-parked LEGACY handoffs — recorded on the trunk with no
# **Deliverable:** field, whose **Beads:** list mixes own work with
# context/epic beads. There the all-closed rule can't fire (a context bead
# never closes) yet branch/PR state is `unknown` (trunk guard), so the row
# renders 🟢 live forever. R_NEEDSREVIEW flags exactly those — partial bead
# closure on a trunk-parked, no-deliverable, otherwise-live current row — so
# the skill can surface a "this may be finished, check it" prompt rather than
# auto-archiving (which could clobber genuinely-live work). Handoffs WITH a
# **Deliverable:** field never need this — they classify cleanly via beadsdone.
R_STATE=()
R_PRSTATE=()
R_PRNUM=()
R_PRURL=()
R_ARCHCLASS=()
R_BEADSDONE=()
R_BEADSPROGRESS=()
R_NEEDSREVIEW=()
R_NEEDSAGEREVIEW=()
R_INACTIVE=() # completion/stale/supersede signal, independent of archive retention
CUR_STALE=0
CUR_AGE_REVIEW=0
WS_STALE=0
WS_AGE_REVIEW=0
# Default every row to "unclassified" up front so the classification passes can
# assign by index. Rows in neither the current repo nor a workspace member keep
# these defaults — we can only speak for repos we can reach.
i=0
while [ "$i" -lt "$N" ]; do
R_STATE+=("unknown")
R_PRSTATE+=("unknown")
R_PRNUM+=("")
R_PRURL+=("")
R_ARCHCLASS+=("")
R_BEADSDONE+=("")
R_BEADSPROGRESS+=("")
R_NEEDSREVIEW+=("")
R_NEEDSAGEREVIEW+=("")
# Session-matched rows are never classified here (their repo is elsewhere),
# so supersede is their only inactivity signal.
if [ "${R_MATCH[$i]}" = "session" ] && [ -n "${R_SUPBY[$i]}" ]; then
R_INACTIVE+=("superseded")
else
R_INACTIVE+=("")
fi
i=$((i+1))
done
# Classify row $1. $2 selects which stale counter this row feeds: `cur` for the
# current repo (drives §3b's stale group), `ws` for a workspace member. The
# caller must have pointed setup_liveness/setup_beads at the row's repo first —
# every lookup in here reads those globals, which is what makes the same logic
# reusable across repos instead of being hard-wired to pwd.
classify_row() {
local i="$1" scope="$2"
local state="unknown" ps="unknown" pnum="" purl="" pcompleted="" completed=""
local archclass="" beadsdone="" beadsprogress="" needsreview="" needsagereview="" inactive=""
local bead_src counts bclosed=0 btotal=0 bcompleted="" beadsunknown="" recordedpr=""
printf '%s' "${R_PRS[$i]}" | grep -qE '#[0-9]+' && recordedpr="Y"
if [ "$CHECK_BRANCHES" -eq 1 ]; then
state=$(branch_state "${R_BRANCH[$i]}")
IFS='|' read -r ps pnum purl pcompleted <<< "$(pr_state "${R_BRANCH[$i]}" "${R_PRS[$i]}")"
fi
# Bead-closure is local — computed whenever beads exist, even without
# --check-branches, so landscape's offline call benefits too. The
# **Deliverable:** field (own-work beads) keys the check when present;
# absent it, fall back to the full **Beads:** field (legacy handoffs).
# Over-inclusion in Deliverable only ever UNDER-detects (a never-closing
# bead keeps the row live) — safe; omitting an own-work bead is the only way
# to false-positive, so wrap-up errs toward including.
if [ -n "$BEADS_AVAILABLE" ]; then
bead_src="${R_DELIV[$i]}"
[ -n "$bead_src" ] || bead_src="${R_BEADS[$i]}"
if counts=$(beads_counts "$bead_src"); then
read -r bclosed btotal bcompleted <<< "$counts"
if [ "$btotal" -gt 0 ]; then
beadsprogress="${bclosed}/${btotal}"
[ "$bclosed" -eq "$btotal" ] && beadsdone="Y"
fi
else
beadsunknown="Y"
fi
fi
if [ -n "${R_SUPBY[$i]}" ]; then
archclass="safe"
elif [ "$ps" = "open" ]; then
archclass=""
elif [ "$ps" = "merged" ]; then
archclass="safe"
completed="$pcompleted"
[ -z "$beadsdone" ] || completed=$(retention latest -- "$pcompleted" "$bcompleted")
elif [ -n "$beadsdone" ]; then
archclass="safe"
completed="$bcompleted"
elif [ "$ps" = "closed" ]; then
archclass="keep"
completed="$pcompleted"
elif [ "$state" = "merged" ]; then
archclass="safe"
elif [ "$state" = "gone" ]; then
archclass="keep"
fi
[ -n "$archclass" ] && inactive="Y"
# Completion status and archive eligibility are separate. Missing clocks
# retain context; ancestry or a vanished branch cannot date its completion.
if [ -z "${R_SUPBY[$i]}" ] && [ -n "$archclass" ] \
&& ! retention expired --handoff-date "${R_DATE[$i]}" --completed-at "$completed" \
--today "$TODAY" --days "$RETENTION_DAYS"; then
archclass=""
fi
# "stale" group = archivable after applying the completion-retention guard,
# but not via supersede.
if [ -z "${R_SUPBY[$i]}" ] && [ -n "$archclass" ]; then
if [ "$scope" = "cur" ]; then CUR_STALE=$((CUR_STALE+1)); else WS_STALE=$((WS_STALE+1)); fi
fi
# Trunk-parked legacy handoff that still renders live but has PARTIAL bead
# closure (something shipped, something open) and no Deliverable field to
# disambiguate → flag for the assisted prompt. All-closed rows already
# became archclass=safe above; all-open rows are genuinely live.
if [ -z "$archclass" ] && [ -z "$inactive" ] && [ -z "${R_DELIV[$i]}" ] \
&& is_trunk_branch "${R_BRANCH[$i]}" && [ -n "$beadsprogress" ] \
&& [ "${beadsprogress%%/*}" -gt 0 ] \
&& [ "$ps" != "open" ] \
&& retention expired --handoff-date "${R_DATE[$i]}" --completed-at "$bcompleted" \
--today "$TODAY" --days "$RETENTION_DAYS"; then
needsreview="Y"
fi
# Age is only a reason to ask, never evidence of completion. Flag old
# current-repo and workspace-member rows when every stronger signal is
# absent: unknown branch liveness, no usable PR signal, no resolvable beads,
# and otherwise unclassified. A successful empty PR lookup is usable proof
# that no PR belongs to this repo even when the handoff links cross-repo PRs;
# an unavailable lookup qualifies only when the handoff records no PR.
if [ "$CHECK_BRANCHES" -eq 1 ] \
&& [ -z "$archclass" ] && [ -z "$inactive" ] && [ -z "$needsreview" ] \
&& [ "$state" = "unknown" ] \
&& { [ "$ps" = "none" ] || { [ "$ps" = "unknown" ] && [ -z "$recordedpr" ]; }; } \
&& [ -z "$beadsprogress" ] && [ -z "$beadsunknown" ] && [ -n "${R_DATE[$i]}" ] \
&& [[ "${R_DATE[$i]}" < "$AGE_REVIEW_CUTOFF" ]]; then
needsagereview="Y"
if [ "$scope" = "cur" ]; then
CUR_AGE_REVIEW=$((CUR_AGE_REVIEW+1))
else
WS_AGE_REVIEW=$((WS_AGE_REVIEW+1))
fi
fi
R_STATE[i]="$state"
R_PRSTATE[i]="$ps"
R_PRNUM[i]="$pnum"
R_PRURL[i]="$purl"
R_ARCHCLASS[i]="$archclass"
R_BEADSDONE[i]="$beadsdone"
R_BEADSPROGRESS[i]="$beadsprogress"
R_NEEDSREVIEW[i]="$needsreview"
R_NEEDSAGEREVIEW[i]="$needsagereview"
R_INACTIVE[i]="$inactive"
}
# Current-repo rows (liveness globals already point at pwd).
if [ "$CURRENT_REPO_KEY" != "NONE" ]; then
i=0
while [ "$i" -lt "$N" ]; do
[ "${R_REPO[$i]}" = "$CURRENT_REPO_KEY" ] && classify_row "$i" cur
i=$((i+1))
done
fi
# Workspace-member rows. Each member needs its own ls-remote + gh + bd, so we
# group by member and set up once per repo rather than once per row — and skip
# members that own no handoffs entirely, since the setup is the expensive part.
# Gated on --check-branches to match the current-repo contract: callers that
# asked for a cheap offline listing don't silently get N repos' network calls.
WS_CLASSIFIED=0
if [ "$CHECK_BRANCHES" -eq 1 ] && [ "${#WS_KEYS[@]}" -gt 0 ]; then
mi=0
while [ "$mi" -lt "${#WS_KEYS[@]}" ]; do
mkey="${WS_KEYS[$mi]}"
has_rows=0
i=0
while [ "$i" -lt "$N" ]; do
if [ "${R_REPO[$i]}" = "$mkey" ]; then has_rows=1; break; fi
i=$((i+1))
done
if [ "$has_rows" -eq 1 ]; then
setup_liveness "${WS_PATHS[$mi]}"
setup_beads "${WS_PATHS[$mi]}"
i=0
while [ "$i" -lt "$N" ]; do
if [ "${R_REPO[$i]}" = "$mkey" ]; then
classify_row "$i" ws
WS_CLASSIFIED=$((WS_CLASSIFIED+1))
fi
i=$((i+1))
done
fi
mi=$((mi+1))
done
# Restore pwd scope so anything downstream reads the current repo again.
setup_liveness "."
setup_beads "."
fi
# --- Current-repo "last session" + live-recent count (offline; for landscape) -
# LATEST_* is the newest current-repo handoff (records are newest-first).
# recent_live counts recent current-repo handoffs without a completion, stale,
# or supersede signal. It uses R_INACTIVE rather than archive-class because the
# retention guard deliberately clears archive-class on recent finished rows.
# So the morning nudge reflects distinct resumable
# threads, not re-wraps of the same one nor work that has already shipped.
CUR_RECENT_LIVE=0
LATEST_SLUG=""
LATEST_BRANCH=""
LATEST_DATE=""
# Per-handoff lines for the recent, non-superseded current-repo handoffs counted
# by CUR_RECENT_LIVE (newest first, same records). Lets landscape enumerate the
# few live threads inline instead of only naming the newest. Always emitted —
# survives --summary-only, since it's the summary-mode caller (landscape) that
# wants it.
CUR_LIVE_LINES=()
if [ "$CURRENT_REPO_KEY" != "NONE" ]; then
i=0
while [ "$i" -lt "$N" ]; do
if [ -n "${R_MATCH[$i]}" ]; then
if [ -z "$LATEST_DATE" ]; then
LATEST_SLUG="${R_SLUG[$i]}"
LATEST_BRANCH="${R_BRANCH[$i]}"
LATEST_DATE="${R_DATE[$i]}"
fi
if [ -z "${R_INACTIVE[$i]}" ] \
&& { [[ "${R_DATE[$i]}" > "$CUTOFF" ]] || [ "${R_DATE[$i]}" = "$CUTOFF" ]; }; then
CUR_RECENT_LIVE=$((CUR_RECENT_LIVE+1))
CUR_LIVE_LINES+=("${R_SLUG[$i]}|${R_BRANCH[$i]}|${R_DATE[$i]}|${R_TIME[$i]}")
fi
fi
i=$((i+1))
done
fi
# Handoffs owned by a workspace member — counted regardless of --check-branches
# so a caller can tell "there are 14 member handoffs" even on a cheap offline run.
WS_HANDOFF_COUNT=0
if [ "${#WS_KEYS[@]}" -gt 0 ]; then
i=0
while [ "$i" -lt "$N" ]; do
ws_index_for_key "${R_REPO[$i]}" >/dev/null && WS_HANDOFF_COUNT=$((WS_HANDOFF_COUNT+1))
i=$((i+1))
done
fi
# --- Emit per-handoff lines (newest first; suppressed in --summary-only) ---
echo "---HANDOFFS---"
if [ "$SUMMARY_ONLY" -eq 0 ]; then
i=0
while [ "$i" -lt "$N" ]; do
emit_record "${R_FILE[$i]}" "${R_DATE[$i]}" "${R_SLUG[$i]}" "${R_CWD[$i]}" "${R_BRANCH[$i]}" "${R_REPO[$i]}" "${R_EXISTS[$i]}" "${R_SUPBY[$i]}" "${R_SUPREASON[$i]}" "${R_STATE[$i]}" "${R_PRSTATE[$i]}" "${R_PRNUM[$i]}" "${R_PRURL[$i]}" "${R_ARCHCLASS[$i]}" "${R_TIME[$i]}" "${R_BEADS[$i]}" "${R_JIRA[$i]}" "${R_BEADSDONE[$i]}" "${R_DELIV[$i]}" "${R_BEADSPROGRESS[$i]}" "${R_NEEDSREVIEW[$i]}" "${R_NEEDSAGEREVIEW[$i]}" "${R_SOURCE[$i]}" "${R_PATH[$i]}" "${R_MATCH[$i]}"
i=$((i+1))
done
fi
# Newest current-repo handoff (the "last session"), or empty line if none.
echo "---CURRENT-REPO-LATEST---"
if [ -n "$LATEST_DATE" ]; then
emit_record "${LATEST_SLUG}" "${LATEST_BRANCH}" "${LATEST_DATE}"
fi
# Recent active current-repo handoffs (newest first) — the live threads behind
# current_repo_recent_live. One `{slug}|{branch}|{date}|{time}` line each. The
# first live row may differ from CURRENT-REPO-LATEST when the newest handoff has
# already completed. Empty when there are none.
echo "---CURRENT-REPO-LIVE---"
if [ "${#CUR_LIVE_LINES[@]}" -gt 0 ]; then
for line in "${CUR_LIVE_LINES[@]}"; do
echo "$line"
done
fi
echo "---SUMMARY---"
echo "total=${TOTAL}"
echo "current_repo_total=${CUR_TOTAL}"
echo "current_repo_recent=${CUR_RECENT}"
echo "current_repo_recent_live=${CUR_RECENT_LIVE}"
echo "current_repo_pruned=${CUR_PRUNED}"
echo "current_repo_superseded=${CUR_SUPERSEDED}"
echo "current_repo_stale=${CUR_STALE}"
echo "current_repo_age_review=${CUR_AGE_REVIEW}"
echo "other_repos=${#OTHER_KEYS[@]}"
echo "pruned_total=${PRUNED_TOTAL}"
echo "superseded_total=${SUPERSEDED_TOTAL}"
echo "unresolved=${UNRESOLVED_COUNT}"
echo "workspace_members=${#WS_KEYS[@]}"
echo "workspace_member_handoffs=${WS_HANDOFF_COUNT}"
echo "workspace_member_stale=${WS_STALE}"
echo "workspace_member_age_review=${WS_AGE_REVIEW}"
echo "workspace_classified=${WS_CLASSIFIED}"
echo "legacy_total=${LEGACY_TOTAL}"
echo "source_collisions=${#COLLISION_LINES[@]}"
echo "---OTHER-REPOS---"
# Sort other-repos by count desc, then by display name asc.
# NOTE: workspace members still appear here. Keeping this section unfiltered is
# deliberate — five skills parse it, and silently shrinking it would change their
# output. Callers that render the WORKSPACE-MEMBER sections should subtract these.
for i in "${!OTHER_KEYS[@]}"; do
emit_record "${OTHER_COUNTS[$i]}" "${OTHER_DISPLAYS[$i]}" "${OTHER_KEYS[$i]}"
done | sort -t'|' -k1,1nr -k2,2 | awk -F'|' '{print $3"|"$1"|"$2}'
# --- Workspace members ---------------------------------------------------------
# The member repos of the multi-repo workspace the cwd belongs to (empty when the
# cwd isn't in one). `{repo-key}|{display}|{path}|{handoff-count}`, in .mgit.conf
# order. The root repo is excluded — it's the current repo.
echo "---WORKSPACE-MEMBER-REPOS---"
mi=0
while [ "$mi" -lt "${#WS_KEYS[@]}" ]; do
c=0
i=0
while [ "$i" -lt "$N" ]; do
[ "${R_REPO[$i]}" = "${WS_KEYS[$mi]}" ] && c=$((c+1))
i=$((i+1))
done
emit_record "${WS_KEYS[$mi]}" "${WS_DISPLAYS[$mi]}" "${WS_PATHS[$mi]}" "${c}"
mi=$((mi+1))
done
# Handoffs belonging to a workspace member (newest first). Same 24 fields as
# ---HANDOFFS---, plus `{member-display}|{member-path}` appended, so a caller can
# reuse its existing parser and read two extra fields; the member path stays the
# final field. It is what a picker must `cd` to before acting — these rows are
# pickable, but only from inside their own repo.
echo "---WORKSPACE-MEMBER-HANDOFFS---"
if [ "$SUMMARY_ONLY" -eq 0 ]; then
i=0
while [ "$i" -lt "$N" ]; do
if wi=$(ws_index_for_key "${R_REPO[$i]}"); then
emit_record "${R_FILE[$i]}" "${R_DATE[$i]}" "${R_SLUG[$i]}" "${R_CWD[$i]}" "${R_BRANCH[$i]}" "${R_REPO[$i]}" "${R_EXISTS[$i]}" "${R_SUPBY[$i]}" "${R_SUPREASON[$i]}" "${R_STATE[$i]}" "${R_PRSTATE[$i]}" "${R_PRNUM[$i]}" "${R_PRURL[$i]}" "${R_ARCHCLASS[$i]}" "${R_TIME[$i]}" "${R_BEADS[$i]}" "${R_JIRA[$i]}" "${R_BEADSDONE[$i]}" "${R_DELIV[$i]}" "${R_BEADSPROGRESS[$i]}" "${R_NEEDSREVIEW[$i]}" "${R_NEEDSAGEREVIEW[$i]}" "${R_SOURCE[$i]}" "${R_PATH[$i]}" "${WS_DISPLAYS[$wi]}" "${WS_PATHS[$wi]}"
fi
i=$((i+1))
done
fi
echo "---SOURCE-COLLISIONS---"
if [ "${#COLLISION_LINES[@]}" -gt 0 ]; then
for line in "${COLLISION_LINES[@]}"; do
echo "$line"
done
fi
# --- Matched handoffs (only under --bead/--ticket) ------------------------
# Current-repo, active handoffs whose Beads/Jira field exactly contains the
# queried ID/KEY. R_INACTIVE excludes superseded, completed, and stale rows even
# when recent retention leaves archive-class empty, so a resume nudge never
# points at dead context — the newer/live tip wins. Emitted
# only when a filter is active; absent otherwise, so existing parsers are
# untouched. Rows arrive newest-first (same order as ---HANDOFFS---).
# Line: {filename}|{date}|{time}|{slug}|{branch}|{exists}|{pr-state}|{pr-number}|{pr-url}|{source}|{path}
if [ -n "$MATCH_FILTER" ]; then
echo "---MATCHED-HANDOFFS---"
i=0
while [ "$i" -lt "$N" ]; do
if [ -n "${R_MATCH[$i]}" ] && [ -z "${R_INACTIVE[$i]}" ]; then
matched=0
if [ -n "$MATCH_BEAD" ] && field_has_token "${R_BEADS[$i]}" "$MATCH_BEAD"; then matched=1; fi
if [ -n "$MATCH_TICKET" ] && field_has_token "${R_JIRA[$i]}" "$MATCH_TICKET"; then matched=1; fi
if [ "$matched" -eq 1 ]; then
emit_record "${R_FILE[$i]}" "${R_DATE[$i]}" "${R_TIME[$i]}" "${R_SLUG[$i]}" "${R_BRANCH[$i]}" "${R_EXISTS[$i]}" "${R_PRSTATE[$i]}" "${R_PRNUM[$i]}" "${R_PRURL[$i]}" "${R_SOURCE[$i]}" "${R_PATH[$i]}"
fi
fi
i=$((i+1))
done
fi
# Every section is emitted so parsers stay shape-stable, but a partial inventory
# must not look complete (or empty) to callers that only check $?.
[ "$STORAGE_STATUS" = "partial" ] && exit 3
exit 0
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |