#!/usr/bin/env bash
#
# capture-flush.sh  -  write what a run has already learned into the durable
# stores, without needing the run to reach its end.
#
# WHY THIS EXISTS
#
# The persistent writes are triage ingest, the learnings ledger distill, the
# knowledge-base append and the code-graph refresh. Phase 5 is, per
# features/code-graph.md, the phase a run is LEAST likely to reach. A run killed
# in Phase 3, a session that hits its context ceiling, a crash after review -
# if the writes waited for Phase 5, each would throw away everything it had
# established, and the next run on the same repo would rediscover it.
#
# So the writes happen here, and Phase 5 is the LAST flush rather than the
# only one. Phase boundaries call this, and so does SessionEnd. Nothing about
# the trigger depends on a model noticing that a moment qualifies: it hangs on
# a phase transition and on process exit, both objectively visible without any
# agent's cooperation.
#
# What it does NOT do: call a model. Everything here is derived from artefacts
# already on disk (triage-output.json) plus agent-state.json. The parts of
# Phase 5 that genuinely need a model - the knowledge-base extraction, the
# per-repo memory synthesis - stay in Phase 5, because a hook cannot think.
#
# Usage:
#   ./capture-flush.sh [--state <agent-state.json>] [--if-stale] [--json] [--quiet]
#
#   --state     the run to flush. Default: resolved from the newest task dir
#               under $HOME/.claude/logs/multi-agent (see resolve_state).
#   --if-stale  flush only when the run did NOT complete Phase 5 - the
#               SessionEnd case. A finished run has already flushed.
#   --json      machine-readable result for a caller that wants to count rows.
#   --quiet     no stdout. Exit status still distinguishes the outcomes.
#
# Exit codes:
#   0  flushed, or nothing to flush (both are fine outcomes)
#   1  bad usage
#
# It never exits non-zero because a store rejected a row. This runs from a hook,
# and a hook that fails a session over a bookkeeping write is worse than the
# bookkeeping it protects. Every failure is reported and swallowed.

set -uo pipefail

STATE=""
IF_STALE=0
JSON=0
QUIET=0

while [ "$#" -gt 0 ]; do
  case "$1" in
    --state)    STATE="${2:-}"; shift 2 || shift ;;
    --if-stale) IF_STALE=1; shift ;;
    --json)     JSON=1; shift ;;
    --quiet)    QUIET=1; shift ;;
    -h|--help)
      echo "usage: $0 [--state <agent-state.json>] [--if-stale] [--json] [--quiet]" >&2
      exit 1 ;;
    *)
      echo "ERR: unexpected arg $1" >&2; exit 1 ;;
  esac
done

LOGS="${LOGS_ROOT:-$HOME/.claude/logs/multi-agent}"
SCRIPTS="$HOME/.claude/scripts"
[ -d "$SCRIPTS" ] || SCRIPTS="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"

say() {
  [ "$QUIET" -eq 1 ] && return 0
  if [ "$JSON" -eq 1 ]; then printf '%s\n' "$1" >&2; else printf '%s\n' "$1"; fi
}

# Resolve the run to flush.
#
# Newest by mtime of agent-state.json, not by directory name: task ids do not
# sort chronologically (PROJ-1002 can run before PROJ-1001 does) and a
# name-sorted pick would flush the wrong run.
resolve_state() {
  [ -d "$LOGS" ] || return 0
  find "$LOGS" -name agent-state.json -type f -maxdepth 4 -print0 2>/dev/null \
    | xargs -0 ls -t 2>/dev/null | head -1
}

if [ -z "$STATE" ]; then
  STATE="$(resolve_state)"
fi

if [ -z "$STATE" ] || [ ! -f "$STATE" ]; then
  say "capture-flush: no run state found - nothing to flush"
  [ "$JSON" -eq 1 ] && printf '{"status":"noop","reason":"no-state"}\n'
  exit 0
fi

if ! command -v jq >/dev/null 2>&1; then
  say "capture-flush: jq unavailable - skipped"
  [ "$JSON" -eq 1 ] && printf '{"status":"skipped","reason":"no-jq"}\n'
  exit 0
fi

TASK_ID=$(jq -r '.taskId // .jiraId // empty' "$STATE" 2>/dev/null)
ARTIFACTS=$(jq -r '.artifactsPath // empty' "$STATE" 2>/dev/null)
WORKTREE=$(jq -r '.worktreePath // empty' "$STATE" 2>/dev/null)
PHASE7=$(jq -r '[.phases[]? | select((.id // "") == "7") | .status] | first // ""' "$STATE" 2>/dev/null)

if [ "$IF_STALE" -eq 1 ] && [ "$PHASE7" = "completed" ]; then
  say "capture-flush: ${TASK_ID:-run} already completed Phase 5 - nothing stale"
  [ "$JSON" -eq 1 ] && printf '{"status":"noop","reason":"already-flushed","taskId":"%s"}\n' "$TASK_ID"
  exit 0
fi

# The triage artefact is the only input either store needs, and it has two homes:
# Phase 4 removes the worktree once the PR is open, so the salvaged copy under
# artifactsPath is tried FIRST. Reading the worktree path first would degrade
# silently for exactly the runs this script exists to rescue.
#
# After those, each worktree's newest `.pipeline/triage-round-<N>.json`: Phase 3
# writes every round there itself, and the copy to triage-output.json is a
# separate step a run can die before. A multi-repo run names its worktrees only
# under projects[], so those are read too, and the state directory last.
newest_round() {
  [ -d "$1/.pipeline" ] || return 0
  ls -t "$1"/.pipeline/triage-round-*.json 2>/dev/null | head -1
}
WORKTREES=$( { [ -n "$WORKTREE" ] && printf '%s\n' "$WORKTREE"; jq -r '.projects[]?.worktreePath // empty' "$STATE" 2>/dev/null; } | awk 'NF && !seen[$0]++')
TRIAGE=""
CANDIDATES=("${ARTIFACTS:+$ARTIFACTS/triage-output.json}")
# Within one worktree the newer of the copy and the newest round wins: a run
# that died before the copy step leaves the previous round in the copy.
newest_in_worktree() {
  local copy="$1/triage-output.json" round
  round=$(newest_round "$1")
  if [ -f "$copy" ] && [ -n "$round" ]; then
    ls -t "$copy" "$round" 2>/dev/null | head -1
  elif [ -f "$copy" ]; then
    printf '%s\n' "$copy"
  else
    printf '%s\n' "$round"
  fi
}
while IFS= read -r wt; do
  [ -n "$wt" ] || continue
  CANDIDATES+=("$(newest_in_worktree "$wt")")
done <<< "$WORKTREES"
CANDIDATES+=("$(dirname "$STATE")/triage-output.json")

# A state below the unattended run root was written by the run, as was its
# directory, and this script may run from a hook outside the sandbox. There the
# triage is read only as a regular JSON file within the run directory
# (lib/regular-file.mjs readRegularJson, no link followed), copied to a private
# temp file the stores read, and the state's `project` never names the store.
_CF_HERE="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
RUN_DIR="$(dirname "$STATE")"
UNATTENDED_STATE=0
# shellcheck source=/dev/null
if [ -f "$_CF_HERE/../lib/run-writable.sh" ]; then
  . "$_CF_HERE/../lib/run-writable.sh"
elif [ -f "$HOME/.claude/lib/run-writable.sh" ]; then
  . "$HOME/.claude/lib/run-writable.sh"
fi
if ! command -v ma_under_run_root >/dev/null 2>&1 || ma_under_run_root "$RUN_DIR"; then
  UNATTENDED_STATE=1
fi
REGULAR_FILE_LIB="$_CF_HERE/../lib/regular-file.mjs"
[ -f "$REGULAR_FILE_LIB" ] || REGULAR_FILE_LIB="$HOME/.claude/lib/regular-file.mjs"
# One private copy for the whole flush, made here in the parent shell: the
# candidates are read inside `$(...)` subshells, and a path assigned there
# never reaches the EXIT trap.
TRIAGE_COPY=""
trap '[ -n "$TRIAGE_COPY" ] && rm -f "$TRIAGE_COPY"' EXIT
if [ "$UNATTENDED_STATE" -eq 1 ]; then
  TRIAGE_COPY=$(mktemp "${TMPDIR:-/tmp}/capture-flush.XXXXXX") || TRIAGE_COPY=""
fi
read_within_run_dir() { # $1 candidate, $2 private copy; prints the copy's path
  [ -f "$REGULAR_FILE_LIB" ] && [ -n "$2" ] || return 1
  node --input-type=module -e '
    import { writeFileSync } from "node:fs";
    import { pathToFileURL } from "node:url";
    const [file, within, out, lib] = process.argv.slice(1);
    const { readRegularJson } = await import(pathToFileURL(lib).href);
    const doc = readRegularJson(file, null, { within: [within], maxBytes: 16 * 1024 * 1024 });
    if (doc === null) process.exit(3);
    writeFileSync(out, JSON.stringify(doc));
  ' "$1" "$RUN_DIR" "$2" "$REGULAR_FILE_LIB" 2>/dev/null || return 1
  printf '%s\n' "$2"
}

for cand in "${CANDIDATES[@]}"; do
  [ -n "$cand" ] || continue
  if [ "$UNATTENDED_STATE" -eq 1 ]; then
    TRIAGE=$(read_within_run_dir "$cand" "$TRIAGE_COPY") && break
    TRIAGE=""
  else
    [ -f "$cand" ] && { TRIAGE="$cand"; break; }
  fi
done

INGESTED="skipped"
DISTILLED="skipped"

# Both writes are idempotent by contract, which is what makes calling this at
# every phase boundary safe: the second call through writes 0 rows.
#
# And 0 rows is a SUCCESS here. Both tools exit 2 on "nothing new", which is the
# normal outcome of every flush after the first - so exit 2 is folded into ok
# rather than reported as failure. Treating it as failure would have made the
# steady state of this script look broken.
run_store() {
  local label="$1"; shift
  local rc=0
  "$@" >/dev/null 2>&1 || rc=$?
  case "$rc" in
    0) printf 'ok' ;;
    2) printf 'ok-nothing-new' ;;
    *) printf 'failed(%s)' "$rc" ;;
  esac
}

# The store is named after the run's repository, never after the directory this
# script happens to run in: a SessionEnd hook fires wherever the session was.
# A live worktree resolves to its main checkout's folder, the same name the
# readers derive; otherwise the project recorded in the state.
slug_of_worktree() {
  [ -d "$1" ] || return 0
  local main
  main=$(git -C "$1" worktree list --porcelain 2>/dev/null | sed -n '1s/^worktree //p')
  [ -n "$main" ] || return 0
  basename "$main" .git
}
SLUG=""
while IFS= read -r wt; do
  [ -n "$wt" ] && [ -z "$SLUG" ] && SLUG=$(slug_of_worktree "$wt")
done <<< "$WORKTREES"
plain_slug() {
  case "$1" in
    "" | .* | *[!A-Za-z0-9._-]*) return 0 ;;
  esac
  printf '%s' "$1"
}
SLUG=$(plain_slug "$SLUG")
if [ -z "$SLUG" ] && [ "$UNATTENDED_STATE" -eq 0 ]; then
  SLUG=$(plain_slug "$(jq -r '.project // .projects[0].name // empty' "$STATE" 2>/dev/null)")
fi
SLUG_ARGS=()
[ -n "$SLUG" ] && SLUG_ARGS=(--repo-slug "$SLUG")

if [ -n "$TRIAGE" ]; then
  INGESTED=$(run_store ingest \
    node "$SCRIPTS/triage-memory.mjs" ingest --triage "$TRIAGE" --state "$STATE" ${SLUG_ARGS[@]+"${SLUG_ARGS[@]}"})
  if [ -n "$TASK_ID" ]; then
    DISTILLED=$(run_store distill \
      node "$SCRIPTS/learnings-ledger.mjs" from-triage --triage "$TRIAGE" --task "$TASK_ID" ${SLUG_ARGS[@]+"${SLUG_ARGS[@]}"})
    DEBT=$(run_store debt \
      node "$SCRIPTS/debt-ledger.mjs" from-run --triage "$TRIAGE" --state "$STATE" --task "$TASK_ID" ${SLUG_ARGS[@]+"${SLUG_ARGS[@]}"})
  fi
fi

# Shortcut markers come from the diff, so they are read while a worktree is
# still there; after Phase 4 removes it the flush has no diff and skips them.
BASE=$(jq -r '.baseBranch // empty' "$STATE" 2>/dev/null)
if [ -n "$TASK_ID" ] && [ -n "$BASE" ] && [ -n "$WORKTREE" ] && [ -d "$WORKTREE" ]; then
  MARKERS=$(run_store markers bash -c 'set -o pipefail; git -C "$1" -c core.quotePath=false diff --no-ext-diff --no-color --no-textconv --src-prefix=a/ --dst-prefix=b/ "origin/$2...HEAD" | node "$3/debt-ledger.mjs" add --patch - --task "$4" "${@:5}"' \
    bash "$WORKTREE" "$BASE" "$SCRIPTS" "$TASK_ID" ${SLUG_ARGS[@]+"${SLUG_ARGS[@]}"})
fi

if [ "$JSON" -eq 1 ]; then
  printf '{"status":"flushed","taskId":"%s","triage":"%s","ingest":"%s","distill":"%s","debt":"%s","markers":"%s"}\n' \
    "$TASK_ID" "${TRIAGE:-none}" "$INGESTED" "$DISTILLED" "${DEBT:-skipped}" "${MARKERS:-skipped}"
fi

if [ -z "$TRIAGE" ]; then
  say "capture-flush: ${TASK_ID:-run} has no triage output yet - nothing to flush"
else
  say "capture-flush: ${TASK_ID:-run} triage=$INGESTED ledger=$DISTILLED"
fi
exit 0
