#!/usr/bin/env bash
{ # Whole script in one group: bash parses it all before running, so editing or
  # redeploying this file while a delegation runs cannot corrupt that run (seen
  # 2026-11-09: 4 benchmark runs died with 'syntax error near done').
# vibe-delegate — Launch Vibe programmatically and capture the result
# Usage: vibe-delegate <workdir> <prompt> [max-turns] [agent] [timeout-secs]
#
# ROOT CAUSE FIX (2026-05-10):
#   vibe checks for a TTY on startup. Without one (e.g. when piped directly),
#   it hangs indefinitely waiting for terminal initialisation → 0 tool calls,
#   silent timeout. Fix: wrap vibe in `script -q -c "..." /dev/null` to allocate
#   a pseudo-TTY. The JSON streaming output is then piped cleanly to the parser.
#
# TTY ALLOCATION (2026-05-23):
#   Superseded the `script` wrapper above with python3 pty.spawn — more portable
#   (no GNU/BSD flag differences) and works even without a parent controlling TTY.
#   See the SCRIPT_CMD definition below for the current implementation.
#
# PROMPT SAFETY (2026-05-12):
#   Long prompts with Python code, dicts, colons, emojis, or accented chars are
#   passed via a temp file (read by vibe via --prompt-file if supported, else via
#   a wrapper that cats the file). This avoids shell injection / truncation bugs.
#
# RUN LOG (2026-05-12):
#   Appends one JSONL entry to ~/.local/share/delegate-runs.jsonl after each run.
#   Fields: ts, delegate, project, prompt_words, agent, max_turns, timeout_secs,
#           exit_code, timed_out, tool_calls, files_changed, syntax_errors,
#           duration_secs, tokens_in, tokens_out, tokens_total, cost_usd, model,
#           warn_count, search_replace_fails, cost_claude_eq, wrote_nothing,
#           failure_reason, adaptations.

# Pull out --require "<string>" flags (repeatable) from anywhere in the args,
# then treat the rest as positional. Each required string must already exist in
# the workdir or the run is aborted before launch (see pre-flight gate below).
REQUIRES=()
INCLUDES=()
POSITIONAL=()
VERBOSE=0
while [ $# -gt 0 ]; do
  case "$1" in
    --require)
      # `shift 2` fails (and shifts nothing) when --require is the last arg, which
      # re-enters this loop forever: a dangling --require hung the caller.
      if [ $# -lt 2 ]; then echo "ERROR: --require needs a string argument" >&2; exit 2; fi
      REQUIRES+=("$2"); shift 2 ;;
    --verbose) VERBOSE=1; shift ;;
    --resume)
      # Continue an earlier Vibe session (its id is printed on every partial run).
      if [ $# -lt 2 ]; then echo "ERROR: --resume needs a session id" >&2; exit 2; fi
      RESUME_SESSION="$2"; RESUME_MODE="explicit"; shift 2 ;;
    --resume-last)
      # Reuse the most recent vibe session recorded for this workdir in the run
      # log (resolved below). For continuation tasks only — the caller decides;
      # never auto-resume unconditionally, a stale unrelated context pollutes runs.
      RESUME_LAST=1; shift ;;
    --no-resume) NO_RESUME=1; shift ;;
    --include)
      # --include path:A-B — inject the verbatim lines A-B of path (inside the
      # workdir) into the prompt as a REFERENCE block, so Vibe does not need to
      # grep/read that region. Repeatable. Capped at DELEGATE_INCLUDE_MAX_BYTES.
      if [ $# -lt 2 ]; then echo "ERROR: --include needs path:A-B" >&2; exit 2; fi
      INCLUDES+=("$2"); shift 2 ;;
    --continue-rounds)
      if [ $# -lt 2 ]; then echo "ERROR: --continue-rounds needs a number" >&2; exit 2; fi
      CONTINUE_ROUNDS="$2"; shift 2 ;;
    --no-continue) CONTINUE_ROUNDS=0; shift ;;
    --allow-code) ALLOW_CODE=1; shift ;;
    --force) FORCE=1; shift ;;
    *) POSITIONAL+=("$1"); shift ;;
  esac
done
set -- "${POSITIONAL[@]}"

WORKDIR="${1:?Usage: vibe-delegate <workdir> <prompt> [max-turns] [agent] [timeout-secs] [--require STR ...] [--include path:A-B ...] [--resume SID | --resume-last | --no-resume] [--force]}"
PROMPT="${2:?Prompt required}"
MAX_TURNS="${3:-10}"
AGENT="${4:-}"
TIMEOUT_SECS="${5:-300}"

# Hard ceiling: SKILL.md has documented "never exceed 12 turns, decompose instead"
# since 2026-05, but nothing enforced it — one observed session (2026-06-17) ran
# a 4-file refactor at max-turns=12 that still only got 2/4 files done for 334k tokens.
# Decomposition was the documented fix; this makes it impossible to skip by accident.
if [ "$MAX_TURNS" -gt 12 ] 2>/dev/null; then
  echo "WARNING: max-turns $MAX_TURNS exceeds the hard cap of 12 — clamping to 12. Decompose the task into sequential runs instead of raising this." >&2
  MAX_TURNS=12
fi

case "$MAX_TURNS" in ''|*[!0-9]*) echo "ERROR: max-turns '$MAX_TURNS' is not a number" >&2; exit 2 ;; esac
case "$TIMEOUT_SECS" in ''|*[!0-9]*) echo "ERROR: timeout-secs '$TIMEOUT_SECS' is not a number" >&2; exit 2 ;; esac
# Turn-budget honesty (2026-11-10): a thinking-model call costs ~60-90s wall
# clock, so a time budget smaller than max-turns x ~80s means the deadline hits
# before the turn cap — the model is told a budget it cannot spend and stops
# mid-task (observed: 12 turns / 480s -> only ~6 ran). Clamp max-turns to what the
# budget allows so the RUN BUDGET line tells the truth and the model writes
# earlier. Override the per-turn cost with DELEGATE_TURN_SECS_PER_TURN.
TURN_SECS="${DELEGATE_TURN_SECS_PER_TURN:-80}"
AFFORDABLE=$(( TIMEOUT_SECS / TURN_SECS ))
if [ "$AFFORDABLE" -ge 1 ] && [ "$MAX_TURNS" -gt "$AFFORDABLE" ]; then
  echo "WARNING: max-turns $MAX_TURNS clamped to $AFFORDABLE (timeout ${TIMEOUT_SECS}s / ~${TURN_SECS}s per model call). Raise timeout-secs or accept fewer turns." >&2
  MAX_TURNS=$AFFORDABLE
fi
CONTINUE_ROUNDS="${CONTINUE_ROUNDS:-2}"
case "$CONTINUE_ROUNDS" in ''|*[!0-9]*) echo "ERROR: --continue-rounds '$CONTINUE_ROUNDS' is not a number" >&2; exit 2 ;; esac
RESUME_SESSION="${RESUME_SESSION:-}"
RESUME_MODE="${RESUME_MODE:-}"
AUTO_RESUME=0
# ── Resume resolution ────────────────────────────────────────────────────────
# Priority: explicit --resume <sid> > --resume-last > auto-detect > fresh session.
# Auto-detect (default; off with --no-resume or DELEGATE_AUTO_RESUME=0): reuse the
# most recent vibe session of this workdir when the previous run was cut by a
# limit (unfinished task = continuation by definition); session still on disk,
# last run < DELEGATE_AUTO_RESUME_MAX_AGE_H (default 24h) old, resume chain <
# DELEGATE_MAX_RESUME_CHAIN (default 3). Lexical prompt-similarity auto-resume was
# tried and REMOVED (2026-11-10): thresholds uncalibrated, never fired in prod —
# --resume-last covers same-feature continuation, decided by the caller.
# The model cannot pick its own session (the id is fixed at launch), so the check
# lives in the launcher — the only place it can. Decision printed to stderr.
if [ -z "$RESUME_SESSION" ] && [ "${NO_RESUME:-0}" != 1 ] && [ "${DELEGATE_AUTO_RESUME:-1}" != "0" ]; then
  RL=$(DELEGATE_RUN_LOG="${DELEGATE_RUN_LOG:-$HOME/.local/share/delegate-runs.jsonl}" \
       RESOLVE_WD="$WORKDIR" RESOLVE_MODE="${RESUME_LAST:+last}" \
       python3 - <<'PYRES'
import json, os, sys
from datetime import datetime, timezone
log = os.environ['DELEGATE_RUN_LOG']
wd = os.path.realpath(os.environ['RESOLVE_WD'])
mode = os.environ.get('RESOLVE_MODE') or 'auto'   # 'auto' | 'last' (empty env = auto)
max_age_h = float(os.environ.get('DELEGATE_AUTO_RESUME_MAX_AGE_H', '24'))
max_chain = int(os.environ.get('DELEGATE_MAX_RESUME_CHAIN', '3'))
vh = os.environ.get('VIBE_HOME') or os.path.join(os.path.expanduser('~'), '.vibe')
LIMIT_STOP = {'turn_cap', 'timeout', 'budget_limit', 'infra_error'}
try:
    lines = open(log, errors='replace').read().splitlines()
except OSError:
    sys.exit(0)
now = datetime.now(timezone.utc)
# Resume-chain cap: count consecutive most-recent same-workdir runs that resumed
# a session (walking back until one did not). Past DELEGATE_MAX_RESUME_CHAIN
# (default 3) auto-resume is refused — a long chain bloats the context and anchors
# the model on stale decisions. Explicit --resume / --resume-last bypass the cap.
chain = 0
for line in reversed(lines):
    line = line.strip()
    if not line:
        continue
    try:
        r0 = json.loads(line)
    except ValueError:
        continue
    if r0.get('delegate') != 'vibe' or os.path.realpath(r0.get('workdir') or '/') != wd:
        continue
    if r0.get('resumed_session'):
        chain += 1
    else:
        break
for line in reversed(lines):
    line = line.strip()
    if not line:
        continue
    try:
        r = json.loads(line)
    except ValueError:
        continue
    if r.get('delegate') != 'vibe' or os.path.realpath(r.get('workdir') or '/') != wd:
        continue
    sid = r.get('session_id') or ''
    if not sid:
        continue
    if not os.path.isfile(os.path.join(vh, 'logs', 'session', 'unified', sid, 'meta.json')):
        continue
    ts = r.get('ts', '')
    age_h = 999.0
    try:
        age_h = (now - datetime.fromisoformat(ts.replace('Z', '+00:00'))).total_seconds() / 3600
    except Exception:
        pass
    if mode == 'auto' and age_h > max_age_h:
        continue
    if mode == 'auto' and chain >= max_chain:
        sys.stderr.write(f"[auto-resume] rejected {sid} (resume chain {chain} >= {max_chain}) — fresh session\n")
        sys.exit(0)
    reason = r.get('failure_reason', '')
    if mode == 'last' or reason in LIMIT_STOP:
        print(f"{sid}|{ts}|{reason}")
        sys.exit(0)
    sys.stderr.write(f"[auto-resume] rejected {sid} (age {age_h:.1f}h, reason {reason or 'ok'}) — fresh session\n")
    sys.exit(0)
PYRES
)
  if [ -n "$RL" ]; then
    RESUME_SESSION="${RL%%|*}"
    _rest="${RL#*|}"; RL_TS="${_rest%%|*}"; RL_REASON="${_rest#*|}"
    if [ "${RESUME_LAST:-0}" = 1 ]; then
      RESUME_MODE="last"
      echo "[resume-last] reusing session $RESUME_SESSION (last vibe run for $WORKDIR: $RL_TS, reason ${RL_REASON:-ok})" >&2
    else
      AUTO_RESUME=1; RESUME_MODE="auto"
      echo "[auto-resume] reusing session $RESUME_SESSION (last run $RL_TS was limit-stopped: ${RL_REASON:-ok}) — pass --no-resume for a fresh session" >&2
    fi
  elif [ "${RESUME_LAST:-0}" = 1 ]; then
    echo "[resume-last] no previous vibe session found for $WORKDIR — starting fresh" >&2
  fi
fi

# Agent mapping (2026-11-09). Vibe 3.0 (installed 2026-10-29) has only four primary
# agents: ask | accept-edits | smart-approve | auto-approve. `plan`, `default`,
# `lean` were removed, and ~/.vibe/agents/*.toml are subagents: passing any of
# them dies at once with "Agent 'plan' not found" (exit 2). Read-only names now
# map to auto-approve with the write tools disabled (verified: writes refused).
READONLY=0
VIBE_AGENT_FLAG=""
case "$AGENT" in
  plan|explore|readonly|planner|architect|code-reviewer|code-architect|code-explorer)
    READONLY=1; VIBE_AGENT_FLAG="auto-approve" ;;
  ""|default|lean|auto-approve) VIBE_AGENT_FLAG="auto-approve" ;;
  *) VIBE_AGENT_FLAG="$AGENT" ;;
esac

# Time budget (2026-11-09). TIMEOUT_SECS is the TOTAL wall-clock budget of the
# whole delegation, auto-continue rounds included: it is never raised. Measured
# on the 19 successful Vibe 3 runs: p50 95 s, max 386 s; 300 s covers 17/19.
# The 3 timeouts were not slowness (one long single-call file generation, two
# re-read loops), so a bigger budget would only have made them fail later.
if [ "$TIMEOUT_SECS" -lt 60 ]; then
  echo "ERROR: timeout-secs must be >= 60 (got $TIMEOUT_SECS)" >&2; exit 2
fi
RUN_START=$(date +%s)
ROUND_LIMIT=$TIMEOUT_SECS

if [ ! -d "$WORKDIR" ]; then
  echo "ERROR: workdir '$WORKDIR' does not exist" >&2
  exit 1
fi

# Pre-flight gate: a search_replace can't match an anchor that isn't in the file,
# so abort before wasting a vibe run if any --require string is absent. Turns the
# "grep the target first" rule into an enforced check; logs a cheap precheck_abort.
if [ "${#REQUIRES[@]}" -gt 0 ]; then
  MISSING=()
  for s in "${REQUIRES[@]}"; do
    # Scope to source: git grep (tracked + untracked, honours .gitignore) in a repo,
    # else recursive grep excluding .git/node_modules. A bare `grep -r` also hit
    # .git packfiles and vendored dirs, so a stale anchor could false-pass.
    if git -C "$WORKDIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
      git -C "$WORKDIR" grep -qF --untracked -e "$s" 2>/dev/null || MISSING+=("$s")
    else
      grep -rqF --exclude-dir=.git --exclude-dir=node_modules -e "$s" "$WORKDIR" 2>/dev/null || MISSING+=("$s")
    fi
  done
  if [ "${#MISSING[@]}" -gt 0 ]; then
    echo "=== PRECHECK ABORT — required string(s) not found in $WORKDIR ==="
    for s in "${MISSING[@]}"; do echo "  missing: $s"; done
    echo "Nothing was launched. Fix the anchor (grep locally) or the workdir, then retry."
    python3 - "$WORKDIR" <<'PYABORT'
import json, os, sys
from pathlib import Path
from datetime import datetime, timezone
wd = sys.argv[1]
LOG = Path(os.environ.get('DELEGATE_RUN_LOG') or Path.home() / '.local' / 'share' / 'delegate-runs.jsonl')
LOG.parent.mkdir(parents=True, exist_ok=True)
entry = {
    'ts': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
    'delegate': 'vibe', 'workdir': wd, 'project': os.path.basename(wd.rstrip('/')),
    'exit_code': 2, 'tool_calls': 0, 'files_changed': 0, 'tokens_total': 0,
    'duration_secs': 0, 'failure_reason': 'precheck_abort',
}
with open(LOG, 'a') as f:
    f.write(json.dumps(entry) + '\n')
PYABORT
    exit 2
  fi
fi

# Model override: /vibe-model-pick writes alias to this flag file.
# VIBE_ACTIVE_MODEL is inherited by the script child process via `script`.
VIBE_MODEL_FLAG="$HOME/.local/share/vibe-model.flag"
VIBE_MODEL_OVERRIDE=""
# DELEGATE_MODEL (env) wins over the flag file: lets a caller or a benchmark pin a
# model alias for one run without touching the user's /vibe-model-pick choice.
if [ -n "${DELEGATE_MODEL:-}" ]; then
  VIBE_MODEL_OVERRIDE="$DELEGATE_MODEL"
  export VIBE_ACTIVE_MODEL="$VIBE_MODEL_OVERRIDE"
elif [ -f "$VIBE_MODEL_FLAG" ]; then
  VIBE_MODEL_OVERRIDE=$(tr -d '[:space:]' < "$VIBE_MODEL_FLAG")
  export VIBE_ACTIVE_MODEL="$VIBE_MODEL_OVERRIDE"
fi
export DELEGATE_VERBOSE="$VERBOSE"

cd "$WORKDIR"
START_NS=$(date +%s%N)
PROMPT_WORDS=$(printf '%s' "$PROMPT" | wc -w | tr -d ' ')
GIT_BEFORE=$(git rev-parse HEAD 2>/dev/null || echo "no-git")

# Big-file guard (2026-09-30). Vibe's read_file caps at ~50 KiB and returns the
# file TRUNCATED; on a large target it then burns its whole turn budget on
# grep/sed exploration and writes nothing (app/__init__.py, 2 of 3 runs). Any
# existing file named in the prompt above 40 KB gets a standing instruction so
# this no longer depends on the caller remembering it.
# Pre-written code guard (2026-11-10). In 36 of 169 real delegations (21 %) Claude
# had already written the code or final text, in the prompt (9) or in a staging
# file the prompt told Vibe to apply "exactly" (28, ~4,800 chars each): Claude
# paid for writing it (output tokens) and then for the delegation. If the code
# is written, applying it directly is cheaper. --allow-code overrides.
PREWRITTEN=$(PROMPT_TEXT="$PROMPT" WD="$WORKDIR" python3 - << 'PYCODE'
import os, re, subprocess, time
p = os.environ["PROMPT_TEXT"]; wd = os.environ["WD"]
code_re = re.compile(r'^\s*(def |class |async def |function |const |let |var |import |from \S+ import |export |return |@\w|<[a-zA-Z][^>]*>|[\w.\[\]"\']+\s*=\s*\S)')
code = sum(1 for ln in p.split("\n") if code_re.match(ln))
staged = []
if re.search(r"verbatim|exactly|character for character|apply (its|the|all)|copy (it|the)", p, re.I):
    for name in set(re.findall(r"[\w./-]+\.(?:txt|md|py|js|ts|json|html|patch|diff)", p)):
        f = os.path.join(wd, name)
        try:
            st = os.stat(f)
        except OSError:
            continue
        if st.st_size > 1500 and time.time() - st.st_mtime < 3600:
            staged.append(f"{name}({st.st_size // 1024}KB)")
print(f"{code}|{' '.join(staged)}")
PYCODE
)
PREWRITTEN_CODE_LINES=${PREWRITTEN%%|*}
PREWRITTEN_STAGED=${PREWRITTEN#*|}
if [ "${PREWRITTEN_CODE_LINES:-0}" -ge 10 ] && [ "${ALLOW_CODE:-0}" != 1 ]; then
  echo "=== PRECHECK ABORT — the prompt already contains ${PREWRITTEN_CODE_LINES} lines of written code ==="
  echo "If the code is written, apply it yourself: delegating it pays for it twice."
  echo "Otherwise describe the goal, the files and the check, and let Vibe write the code."
  echo "(Override: --allow-code.) Nothing was launched."
  exit 2
fi
if [ -n "$PREWRITTEN_STAGED" ]; then
  echo "[PREFLIGHT] WARNING: the prompt asks Vibe to apply recently written file(s) exactly: $PREWRITTEN_STAGED. If you wrote that content, applying it yourself is cheaper than delegating." >&2
fi

# ── Launch preflight (2026-11-11): blocking refusals ────────────────────────
# The read-burn failures came from prompts naming too many reference files or
# saying "read X first"; headerless prompts and fresh runs over recent sessions
# burn the budget the same way. Every rule below refuses BEFORE vibe is
# launched (exit 2) — nothing is spent. --force bypasses all of them and the
# bypassed rule names are logged as preflight_forced in the run entry (PYLOG).
VIOLATION_NAMES=()
VIOLATION_MSGS=()
pf_add() { VIOLATION_NAMES+=("$1"); VIOLATION_MSGS+=("$2"); }
# Rule 1: TASK/MODIFY headers — a prompt without them delegates nothing.
# Skipped on a resumed session: its task is already in the history, and the
# printed resume hint is a bare "continue" prompt.
if [ -z "${RESUME_SESSION:-}" ]; then
  printf '%s' "$PROMPT" | grep -q '^[[:space:]]*TASK:'   || pf_add missing_task_header "missing TASK: header — the prompt must state one imperative"
  if [ "$READONLY" != 1 ]; then
    printf '%s' "$PROMPT" | grep -q '^[[:space:]]*MODIFY:' || pf_add missing_modify_header "missing MODIFY: header — list the files to change (read-only agents may omit it)"
  fi
fi
# Files to modify are not reads: a mechanical change across 10 files is one run.
MODIFY_FILES=$(printf '%s\n' "$PROMPT" | grep -E '^[[:space:]]*MODIFY:' | head -1 | sed 's/^[[:space:]]*MODIFY:[[:space:]]*//' | tr ',' '\n' | sed 's/^[[:space:]]*//; s/[[:space:]].*//' | grep .)
# Ground truth for the PYLOG delegation report: the declared files, captured
# before any harness text is appended to the prompt below.
export DELEGATE_MODIFY_FILES="$MODIFY_FILES"
PROMPT_FILES=$(printf '%s' "$PROMPT" | grep -oE '[A-Za-z0-9_./-]+\.(py|js|ts|jsx|tsx|html|json|md|sh|css|ya?ml|toml|txt|csv)' | sort -u | grep -vxF -f <(printf '%s\n' "${MODIFY_FILES:-/dev/null/none}"))
N_FILES=$(printf '%s\n' "$PROMPT_FILES" | grep -c .)
# Rule 2: > 4 named files — extra reads burn the time budget.
if [ "$N_FILES" -gt 4 ]; then
  pf_add too_many_files "prompt names $N_FILES files (rule: <= 4) — pass the needed regions with --include path:A-B instead"
  echo "[PREFLIGHT] files: $(printf '%s' "$PROMPT_FILES" | tr '\n' ' ')" >&2
fi
# Rule 3: "read ... first" — say what to extract instead of a blanket read.
if printf '%s' "$PROMPT" | grep -qiE 'read [a-z0-9_./-]+ first|read (the )?(file|reference)s? first'; then
  pf_add read_first "prompt says 'read ... first' — say what to extract (grep -n anchors), or use --include path:A-B"
fi
# Rule 4: more than one not-yet-existing MODIFY file with a short budget —
# scaffolding blank files is slow; more than one does not fit under 480 s.
MODIFY_LINE=$(printf '%s\n' "$PROMPT" | grep -E '^[[:space:]]*MODIFY:' | head -1 | sed 's/^[[:space:]]*MODIFY:[[:space:]]*//')
if [ -n "$MODIFY_LINE" ]; then
  UNBORN=0; UNBORN_LIST=""
  IFS=',' read -r -a _mfiles <<< "$MODIFY_LINE"
  for _f in "${_mfiles[@]}"; do
    _f="${_f#"${_f%%[![:space:]]*}"}"; _f="${_f%%[[:space:]]*}"
    case "$_f" in ''|none|-|n/a) continue ;; esac
    if [ ! -f "$_f" ] && [ ! -f "$WORKDIR/$_f" ]; then
      UNBORN=$((UNBORN+1)); UNBORN_LIST="$UNBORN_LIST $_f"
    fi
  done
  if [ "$UNBORN" -gt 1 ] && [ "$TIMEOUT_SECS" -lt 480 ]; then
    pf_add unborn_files_short_timeout "MODIFY lists $UNBORN file(s) not on disk yet ($UNBORN_LIST) with timeout-secs ${TIMEOUT_SECS}s — creating more than one new file needs >= 480"
  fi
fi
# Rule 5: a vibe run for this workdir finished < 2 h ago and no resume choice
# was made — the caller must pick --resume-last (continue) or --no-resume.
if [ -z "${RESUME_SESSION:-}" ] && [ "${RESUME_LAST:-0}" != 1 ] && [ "${NO_RESUME:-0}" != 1 ]; then
  RECENT_RUN=$(DELEGATE_RUN_LOG="${DELEGATE_RUN_LOG:-$HOME/.local/share/delegate-runs.jsonl}" PREFLIGHT_WD="$WORKDIR" python3 - <<'PYRECENT'
import json, os, sys
from datetime import datetime, timezone
try:
    lines = open(os.environ['DELEGATE_RUN_LOG'], errors='replace').read().splitlines()
except OSError:
    sys.exit(0)
wd = os.path.realpath(os.environ['PREFLIGHT_WD'])
now = datetime.now(timezone.utc)
for line in reversed(lines):        # most recent matching run decides
    line = line.strip()
    if not line:
        continue
    try:
        r = json.loads(line)
    except ValueError:
        continue
    if r.get('delegate') != 'vibe' or os.path.realpath(r.get('workdir') or '/') != wd:
        continue
    try:
        age_h = (now - datetime.fromisoformat(r.get('ts', '').replace('Z', '+00:00'))).total_seconds() / 3600
    except Exception:
        continue
    if age_h < 2:
        print('yes')
    sys.exit(0)
PYRECENT
)
  if [ "$RECENT_RUN" = "yes" ]; then
    pf_add recent_run_no_resume_flag "a vibe run for this workdir finished < 2 h ago — pass --resume-last (continue) or --no-resume (fresh)"
  fi
fi
if [ "${#VIOLATION_NAMES[@]}" -gt 0 ]; then
  if [ "${FORCE:-0}" = 1 ]; then
    DELEGATE_PREFLIGHT_FORCED="$(IFS=,; echo "${VIOLATION_NAMES[*]}")"
    export DELEGATE_PREFLIGHT_FORCED
    echo "[PREFLIGHT] --force: bypassing ${#VIOLATION_NAMES[@]} rule(s) [$DELEGATE_PREFLIGHT_FORCED] — launching anyway" >&2
  else
    echo "=== PREFLIGHT REFUSAL — nothing was launched ===" >&2
    for _i in "${!VIOLATION_MSGS[@]}"; do echo "  - ${VIOLATION_MSGS[$_i]}" >&2; done
    echo "Required prompt format:" >&2
    echo "  TASK: <one imperative>" >&2
    echo "  MODIFY: a.py, b.py   (read-only agents may omit MODIFY)" >&2
    echo "(Fix the prompt, or pass --force to bypass all refusals.)" >&2
    exit 2
  fi
fi

BIG_LIST=""
for _f in $(printf '%s' "$PROMPT" | grep -oE '[A-Za-z0-9_./-]+\.(py|js|html|json|md|sh|css|ya?ml|toml|txt)' | sort -u); do
  if [ -f "$_f" ] && [ "$(stat -c %s "$_f" 2>/dev/null || echo 0)" -gt 40000 ]; then
    BIG_LIST="$BIG_LIST $_f($(( $(stat -c %s "$_f") / 1024 ))KB)"
  fi
done
if [ -n "$BIG_LIST" ]; then
  echo "[PREFLIGHT] large file(s) over one read_file window (50 KiB):$BIG_LIST — injecting grep/offset instruction" >&2
  # Measured 2026-10-01 (docs/harness-audit-2026-10-01.md H8): read_file returns
  # the first 51,200 bytes with was_truncated=true; offset/limit page the rest.
  # Vibe's system prompt forbids editing an unread file, so point it at a
  # targeted read instead of forbidding reads.
  PROMPT="$PROMPT

HARNESS NOTE: these files are larger than one read_file window (50 KiB):$BIG_LIST. Do not read them from the top. Find the line with grep -n, read only that region with read_file offset/limit, then change it with the edit tool using the exact text you just read."
fi
# The model is never told its --max-turns budget (H10); without it a capped run
# just stops mid-task with exit 0 (H2). Name the edit tool by its model-facing
# name: asking for "search_replace" made Vibe spend turns on search_tool_functions (H4).
PROMPT="$PROMPT

RUN BUDGET: $MAX_TURNS turns total; one model call can cost 60-90s, so a time limit can hit after a few turns. WRITE EARLY: first file write within your first 3 turns. Read smart: grep -n the 2-4 anchors you need, read only the matched region, batch ALL independent reads in ONE call, never re-read a file, verify with grep. In-place changes: use the edit tool (batch many edits in one turn via tools.file_system.edit from run_typescript). Keep your last turn for a short summary. Partial writes count: what is on disk when the run is cut stays there.

CHECKS: run only quick, targeted checks (one test file, one import, one script), each well under 60 s. Never run a full build, a whole-project type-check or the whole test suite: the caller verifies afterwards, and a long command can eat the run's whole time budget.

GIT: do not commit, push, stash, reset or switch branches. Leave every change uncommitted in the working tree: the caller reviews the diff and commits.

END REPORT: end your final message with exactly these five lines, a few words each, 'none' when empty:
DONE: <what is finished>
NOT DONE: <what is left>
ASSUMED: <guesses you made>
BLOCKED: <what stopped you>
CHECK: <what the caller should check>"
if [ "$READONLY" = 1 ]; then
  PROMPT="$PROMPT

READ-ONLY RUN: do not modify, create or delete any file (file write tools are disabled; do not use bash to write either). Report your findings as your final answer."
fi
# Injected whenever the run continues an existing session (explicit --resume,
# --resume-last, or auto-resume): the previous task is in the history, its files
# are on disk — re-reading or redoing it is what burns the budget (2026-11-10:
# a fresh session re-read the target file 5 times, 244k tokens, 0 files, turn_cap).
if [ -n "$RESUME_SESSION" ]; then
  PROMPT="$PROMPT

RESUMED SESSION: you are continuing an existing session for this workdir — the previous task is in this history and its files are on disk. Do NOT re-read files you already read in this session, and do NOT redo completed work; if unsure what is already done, run git status --short and git diff --stat first. The new task below builds on that state."
fi
# --include path:A-B: inject verbatim line regions into the prompt as REFERENCE
# blocks, so Vibe uses them directly instead of grepping/reading those files.
if [ "${#INCLUDES[@]}" -gt 0 ]; then
  INCLUDE_BLOCK=$(INCLUDES_NL="$(printf '%s\n' "${INCLUDES[@]}")" WD="$WORKDIR" python3 - <<'PYINC'
import os, sys
wd = os.path.realpath(os.environ['WD'])
max_bytes = int(os.environ.get('DELEGATE_INCLUDE_MAX_BYTES', '8000'))
out, total = [], 0
for item in os.environ['INCLUDES_NL'].splitlines():
    item = item.strip()
    if not item:
        continue
    path, _, rng = item.rpartition(':')
    try:
        a_s, _, b_s = rng.partition('-')
        a, b = int(a_s), int(b_s or a_s)
    except ValueError:
        sys.stderr.write(f"[include] bad range, skipped: {item}\n"); continue
    ap = os.path.realpath(os.path.join(wd, path))
    if not ap.startswith(wd + os.sep) or not os.path.isfile(ap):
        sys.stderr.write(f"[include] not a file inside workdir, skipped: {item}\n"); continue
    lines = open(ap, errors='replace').read().splitlines()
    a = max(1, min(a, len(lines))); b = max(a, min(b, len(lines)))
    chunk = '\n'.join(lines[a-1:b])
    if total + len(chunk) > max_bytes:
        chunk = chunk[:max(0, max_bytes - total)] + "\n... [truncated at DELEGATE_INCLUDE_MAX_BYTES]"
    total += len(chunk)
    out.append(f"REFERENCE {path}:{a}-{b} (verbatim — use directly, do NOT re-read or grep this region):\n```\n{chunk}\n```")
print('\n\n'.join(out))
PYINC
)
  if [ -n "$INCLUDE_BLOCK" ]; then
    PROMPT="$PROMPT

$INCLUDE_BLOCK"
  fi
fi
AUDIT_RC=0

# Sentinel file for mtime-based change detection. `git diff --name-only` is binary
# (modified-vs-not), so it misses a re-edit to a file that was ALREADY dirty before
# this run started — exactly what happens with sequential same-file delegations,
# which RC-2 itself recommends as the mitigation for parallel edits. It also reports
# nothing at all in a non-git workdir. mtime-since-sentinel catches every real write
# regardless of prior git state.
SENTINEL=$(mktemp /tmp/vibe-sentinel-XXXXXX)

echo "=== VIBE START ==="
echo "Workdir : $WORKDIR"
echo "Agent   : ${AGENT:-auto-approve}$([ "$READONLY" = 1 ] && echo " (read-only: auto-approve, write tools disabled)")"
[ -n "$RESUME_SESSION" ] && echo "Resume  : $RESUME_SESSION"
echo "Model   : ${VIBE_MODEL_OVERRIDE:-(config default)}"
echo "Turns   : $MAX_TURNS"
echo "Timeout : ${TIMEOUT_SECS}s total (all rounds)"
echo "Prompt  : ${PROMPT:0:120}..."
echo "==================="

# Write prompt to a temp file — avoids shell injection when prompt contains
# colons, quotes, emojis, accented chars, or multi-line Python/JS code.
PROMPT_FILE=$(mktemp /tmp/vibe-prompt-XXXXXX.txt)
printf '%s' "$PROMPT" > "$PROMPT_FILE"

# Write the vibe command to a temp script.
# Reads the prompt from the file to stay safe from shell expansion.
VIBE_SCRIPT=$(mktemp /tmp/vibe-cmd-XXXXXX.sh)

# Stats handoff file: Python parser writes JSON here; bash reads it for the log.
DELEGATE_STATS_FILE=$(mktemp /tmp/delegate-stats-XXXXXX.json)
printf '{}' > "$DELEGATE_STATS_FILE"
export DELEGATE_STATS_FILE

# Final failure_reason handoff (PYLOG -> bash) so the script can exit non-zero.
DELEGATE_REASON_FILE=$(mktemp /tmp/delegate-reason-XXXXXX.txt)
export DELEGATE_REASON_FILE

# Per-run dir: one --output-dir per round. Vibe 3 writes export.json there on
# EVERY exit (outcome, stop_reason, session_id, usage): the ground truth that
# replaces guessing the session from mtimes.
RUN_DIR=$(mktemp -d /tmp/vibe-run-XXXXXX)

trap 'rm -rf "$VIBE_SCRIPT" "$PROMPT_FILE" "$DELEGATE_STATS_FILE" "$DELEGATE_REASON_FILE" "$SENTINEL" "$RUN_DIR"' EXIT

# write_vibe_script <prompt-file> <resume-session-id or ""> <output-dir>
write_vibe_script() {
  local _resume=""
  [ -n "$2" ] && _resume="--resume $(printf '%q' "$2")"
  local _ro=""
  # Tool names verified on Vibe 3.0.3 (2026-11-09): disabling these refuses writes.
  [ "$READONLY" = 1 ] && _ro="--disabled-tools write_file --disabled-tools search_replace --disabled-tools edit"
  {
    echo '#!/usr/bin/env bash'
    echo "PROMPT_CONTENT=$(printf '%q' "$(cat "$1")")"
    # --time-limit: Vibe stops itself cleanly (exit 3, outcome deadline) and still
    # writes the export. The outer `timeout` only SIGTERMs the pty wrapper, never
    # Vibe, so a killed run left no export, no tokens, no diagnosis (verified).
    # The obsolete --legacy-harness/--experimental-harness flags are gone in Vibe 3.
    printf 'exec vibe --agent %q %s %s -p "$PROMPT_CONTENT" --trust --max-turns %q --time-limit %q --output-dir %q --output streaming --workdir %q\n' \
      "$VIBE_AGENT_FLAG" "$_resume" "$_ro" "$MAX_TURNS" "$ROUND_LIMIT" "$3" "$WORKDIR"
  } > "$VIBE_SCRIPT"
  chmod +x "$VIBE_SCRIPT"
}

# Pseudo-TTY for vibe via python pty.spawn (works without a parent TTY, unlike `script`).
SCRIPT_CMD=(python3 -c 'import pty,sys,os; sys.exit(os.waitstatus_to_exitcode(pty.spawn(sys.argv[1:])))' "$VIBE_SCRIPT")

run_round() {
# Outer backstop only: Vibe's own --time-limit (ROUND_LIMIT) fires first.
BACKSTOP_SECS=$(( ROUND_LIMIT + 60 ))
timeout -k 15 "$BACKSTOP_SECS" "${SCRIPT_CMD[@]}" | python3 -c "
import sys, json, re, os

ANSI_RE = re.compile(r'\x1b\[[0-9;]*[mABCDEFGHJKSTfhilmnprsu]|\x1b\([AB]|\x0f|\x0e')
# Everything unprintable except tab / newline / CR.
CTRL_RE = re.compile(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]')
tools_called = 0
warn_count = 0
sr_fails = 0
sandbox_blocked = False
denied_count = 0
writes = []
def clean(line):
    line = line.replace('\r', '')
    return ANSI_RE.sub('', line).strip()

def safe(s):
    # clean() only strips escapes from the RAW stdin line. An ESC written as
    # an escaped-unicode literal (backslash-u-001b) inside a JSON string value
    # arrives here escape-free, so clean() sees nothing to strip; json.loads
    # then decodes it back into a real ESC, which reaches stdout when printed.
    # A tool name, path or denial reason can therefore repaint the terminal
    # (erase-line, cursor-up) and forge output. That matters twice over: this
    # text is read by a terminal AND fed back to the orchestrating model.
    # So strip at every print of a decoded value, not just on the raw line.
    return CTRL_RE.sub('', ANSI_RE.sub('', str(s)))

def as_text(content):
    # Vibe emits message content EITHER as a plain string (session-log /
    # legacy schema) OR as a list of content blocks (current --output
    # streaming schema: [{'type': 'text', 'text': ...}]). Calling .lower()
    # straight on the list crashed the whole parser and threw away the run
    # output, so normalise to str once, here, before anything touches it.
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        parts = []
        for blk in content:
            if isinstance(blk, dict):
                parts.append(blk.get('text') or blk.get('content') or '')
            elif isinstance(blk, str):
                parts.append(blk)
        return chr(10).join(p for p in parts if p)
    if content is None:
        return ''
    return str(content)

for raw in sys.stdin:
    line = clean(raw)
    if not line:
        continue
    try:
        msg = json.loads(line)
    except json.JSONDecodeError:
        # vibe reports startup failures as PLAIN TEXT on stdout, not JSON —
        # e.g. 'Error: Agent X not found' or 'Agent X is a subagent and cannot
        # be used as the primary agent'. Silently swallowing every non-JSON
        # line meant those surfaced only as exit 1 after 1.5s with no reason.
        low = line.lower()
        if low.startswith('error') or 'not found' in low or 'cannot be used' in low or 'usage:' in low:
            warn_count += 1
            print(f'  [ERROR] {safe(line)[:200]}', flush=True)
        continue

    role    = msg.get('role', '')
    content = as_text(msg.get('content', ''))
    etype   = msg.get('type', '')

    if role in ('system', 'user'):
        continue

    if 'not permitted' in content.lower():
        sandbox_blocked = True

    # ── streaming schema: tool calls arrive as 'effect', not role='tool' ──
    # Without this the run reports 'Tool calls: 0' even when the agent read
    # and wrote files, which then mislabels a fine run as WROTE_NOTHING.
    if etype == 'effect':
        detail = msg.get('detail') or {}
        tool_name = safe(detail.get('toolName') or msg.get('title') or '')
        kind = detail.get('kind') or ''
        tinput = detail.get('input') or {}
        # read_file / write_file carry the target as 'path' (H7).
        filepath = safe(tinput.get('filePath') or tinput.get('file_path') or tinput.get('path') or '')
        state = msg.get('state') or {}
        status = state.get('status') or ''
        disp = state.get('display') or {}
        tools_called += 1
        _why = safe(disp.get('message') or state.get('reason') or '')
        if status in ('cancelled', 'skipped') and 'interrupt' in _why.lower():
            # The run stopping (--time-limit deadline, turn end) interrupts the
            # running tool: that is not an approval refusal.
            print(f'  [STOPPED] {tool_name} {filepath} - {_why} (run ended mid-call)', flush=True)
        elif status in ('cancelled', 'skipped'):
            # A denied approval lands here. Silent in the old parser: the run
            # exited 0 having done nothing, with no hint why.
            # 'skipped' matters too: project_effect_state tests event.cancelled
            # first and event.skipped second, so a denial carrying a custom
            # decision.feedback — and every pre-tool hook denial — arrives as
            # SkippedEffectState and was being printed as a plain [WARN].
            denied_count += 1
            sandbox_blocked = True
            reason = safe(disp.get('message') or state.get('reason') or 'denied')
            print(f'  [DENIED] {tool_name} {filepath} - {reason}', flush=True)
        elif kind in ('file_write', 'file_edit') or 'write' in tool_name.lower() or 'edit' in tool_name.lower():
            if filepath:
                writes.append(filepath)
            if 'search_replace' in tool_name.lower():
                ok = disp.get('success', True)
                if not ok:
                    sr_fails += 1
                sr_status = 'OK' if ok else 'FAIL'
                print(f'  [tool]  search_replace [{sr_status}] {filepath}', flush=True)
            else:
                print(f'  [tool]  file: {filepath or tool_name}', flush=True)
        elif kind == 'file_read' or 'read' in tool_name.lower():
            print(f'  [read]  {filepath or tool_name}', flush=True)
        else:
            summary = safe(disp.get('message') or (detail.get('display') or {}).get('summary') or '')
            print(f'  [tool]  {tool_name}: {summary[:100]}', flush=True)
        if disp.get('success') is False and status not in ('cancelled', 'skipped'):
            warn_count += 1
            # Print it — a counted-but-invisible warn is useless. The common
            # one is 'Output (N KiB) exceeds maximum allowed size (50.0 KiB)',
            # which means the agent silently saw only PART of the file.
            failmsg = safe(disp.get('message') or state.get('reason') or '')
            if failmsg:
                print(f'  [WARN]  {tool_name}: {failmsg[:160]}', flush=True)
        continue

    # Approval prompts that need a human: also invisible before.
    if etype == 'callback' and (msg.get('detail') or {}).get('kind') == 'approval':
        perms = (msg.get('detail') or {}).get('requiredPermissions') or []
        labels = ', '.join(safe(p.get('label', '')) for p in perms if isinstance(p, dict))
        cb_title = safe(msg.get('title', '') or '')
        print(f'  [APPROVAL] {cb_title} {labels}', flush=True)
        continue

    if etype == 'reasoning':
        continue

    if role == 'assistant':
        # Escapes stripped, text kept — legitimate output must survive intact.
        text = safe(content).strip()
        if not text:
            continue
        print(f'  [vibe] {text[:400]}', flush=True)

    elif role == 'tool':
        tools_called += 1
        first_line = safe(content.split('\n')[0]) if content else ''
        tool_name  = safe(msg.get('tool', '') or msg.get('name', ''))

        # Detect writes to track files for syntax check
        if 'write' in tool_name.lower() or 'edit' in tool_name.lower():
            filepath = safe(msg.get('path') or msg.get('file_path') or '')
            if filepath:
                writes.append(filepath)
            print(f'  [tool]  file: {filepath or first_line[:80]}', flush=True)
        elif first_line.startswith('path:'):
            print(f'  [read]  {first_line[5:].strip()}', flush=True)
        elif 'search_replace' in tool_name.lower() or 'SEARCH' in content:
            status = 'FAIL' if 'failed' in content.lower() else 'OK'
            if status == 'FAIL':
                sr_fails += 1
            print(f'  [tool]  search_replace [{status}] {first_line[:80]}', flush=True)
        elif first_line.startswith('error') or 'Error' in first_line or 'failed' in first_line.lower():
            warn_count += 1
            print(f'  [WARN]  {first_line[:120]}', flush=True)
        elif 'matches:' in first_line or 'grep' in tool_name.lower():
            print(f'  [tool]  matches: {first_line[:100]}', flush=True)
        elif 'command' in tool_name.lower():
            print(f'  [tool]  command: {first_line[:100]}', flush=True)
        else:
            snippet = safe(first_line or content)[:100]
            print(f'  [tool]  {snippet}', flush=True)

_denied_note = f'  |  DENIED: {denied_count}' if denied_count else ''
print(f'Tool calls: {tools_called}  |  warns: {warn_count}  |  sr_fails: {sr_fails}{_denied_note}')
if denied_count:
    print('  ^ tool calls were DENIED (approval refused). Common cause: a path')
    print('    outside the workdir — --trust does not cover those. Move the file')
    print('    inside the workdir and re-run.')

# Write partial stats so the token block can merge into it.
_sf = os.environ.get('DELEGATE_STATS_FILE', '')
if _sf:
    # Accumulate across auto-continue rounds instead of overwriting.
    try:
        prev = json.load(open(_sf))
    except Exception:
        prev = {}
    try:
        with open(_sf, 'w') as _f:
            json.dump({'tool_calls': prev.get('tool_calls', 0) + tools_called,
                       'warn_count': prev.get('warn_count', 0) + warn_count,
                       'search_replace_fails': prev.get('search_replace_fails', 0) + sr_fails,
                       'sandbox_blocked': bool(prev.get('sandbox_blocked')) or sandbox_blocked,
                       'denied_count': prev.get('denied_count', 0) + denied_count}, _f)
    except Exception:
        pass
"
return "${PIPESTATUS[0]}"
}

# read_export <dir> → prints "outcome|session_id|steps|error message" ("" if no export).
# A 4xx from the model API (except 429 rate limit) is a request the provider will
# refuse again (e.g. "reasoning_effort 'none' is not supported for this model"):
# resuming it only burns another round. Seen 2026-11-09, 8/8 runs.
is_permanent_api_error() {
  printf '%s' "$1" | grep -qE 'Status 4[0-9][0-9]' && ! printf '%s' "$1" | grep -q 'Status 429'
}

read_export() {
  python3 - "$1/export.json" << 'PYEXP'
import json, sys
try:
    d = json.load(open(sys.argv[1]))
except (OSError, ValueError):
    print(''); sys.exit(0)
err = ((d.get('error') or {}).get('message') or '').replace('|', '/').replace('\n', ' ')
print(f"{d.get('outcome') or ''}|{d.get('session_id') or ''}|{d.get('steps') or 0}|{err[:200]}")
PYEXP
}

# ── Rounds: run, then auto-continue the SAME session when Vibe stopped on its
# turn limit (or a transient API failure). Measured 2026-11-09: since the Vibe 3
# upgrade, 7 of 12 failed runs were exit 3 = turn_limit (12 model calls of 12),
# previously logged as a crash. A resumed session keeps its context, so it does
# not re-read anything: verified, a turn-limited run resumed with
# `--resume <id> -p continue` finished the task (5/5 files) in 3 more calls.
# A resumed session's runtime-state already lists the earlier run's actions; the
# WRITE AUDIT must skip them, or their files (untouched in THIS run) would show
# as MISMATCH and fail the run.
AUDIT_SKIP_SEQ=0
if [ -n "$RESUME_SESSION" ]; then
  AUDIT_SKIP_SEQ=$(python3 - "${VIBE_HOME:-$HOME/.vibe}/logs/session/unified/$RESUME_SESSION" << 'PYSKIP'
import glob, json, sys
last = 0
for f in glob.glob(sys.argv[1] + "/journal/*.jsonl"):
    for line in open(f, errors="replace"):
        try:
            last = max(last, int(json.loads(line).get("sequence") or 0))
        except (ValueError, AttributeError, TypeError):
            pass
print(last)
PYSKIP
)
fi
export AUDIT_SKIP_SEQ

ROUND=0
CONTINUED=0
INFRA_RETRIED=0
CUR_PROMPT_FILE="$PROMPT_FILE"
CUR_SID="$RESUME_SESSION"
OUTCOMES=""
while :; do
  OUT_DIR="$RUN_DIR/round-$ROUND"
  write_vibe_script "$CUR_PROMPT_FILE" "$CUR_SID" "$OUT_DIR"
  run_round
  VIBE_EXIT=$?
  IFS='|' read -r R_OUTCOME R_SID R_STEPS R_ERR <<< "$(read_export "$OUT_DIR")"
  [ -n "$R_SID" ] && CUR_SID="$R_SID"
  OUTCOMES="$OUTCOMES ${R_OUTCOME:-noexport(exit $VIBE_EXIT)}"
  [ -n "$R_ERR" ] && echo "  [VIBE ERROR] $R_ERR"
  NEXT=""
  if [ "$R_OUTCOME" = "turn_limit" ] && [ "$CONTINUED" -lt "$CONTINUE_ROUNDS" ] && [ -n "$CUR_SID" ]; then
    # CONTINUED is only incremented once the round is actually launched (below):
    # incrementing here logged auto_continued=1 on runs where the budget check
    # then broke the loop and no continuation round ever ran (seen 2026-11-10).
    NEXT="turn limit reached — continuing the same session ($((CONTINUED + 1))/$CONTINUE_ROUNDS)"
  elif [ "$R_OUTCOME" = "infrastructure_failure" ] && [ "${R_STEPS:-0}" -gt 0 ] && ! is_permanent_api_error "$R_ERR" && [ "$INFRA_RETRIED" -eq 0 ] && [ -n "$CUR_SID" ]; then
    # steps > 0: the agent did run, so this is the model API failing mid-run
    # (e.g. IncompleteProviderStream), not a bad flag/agent (those have 0 steps).
    INFRA_RETRIED=1; NEXT="model API failed mid-run — resuming the same session once"
  fi
  if [ -z "$NEXT" ] && [ "$AUTO_RESUME" = 1 ] && [ "$ROUND" -eq 0 ] \
     && { [ "$R_OUTCOME" = "usage_error" ] || [ "$R_OUTCOME" = "config_error" ]; } \
     && [ "${R_STEPS:-0}" -eq 0 ] && [ -n "$CUR_SID" ]; then
    # The auto-resumed session was rejected by vibe itself (stale/corrupt):
    # fall back to one fresh session instead of dying with usage_error.
    echo "  [auto-resume] session $CUR_SID rejected (${R_OUTCOME}, 0 steps) — starting a fresh session once"
    CUR_SID=""; AUTO_RESUME=0; AUDIT_SKIP_SEQ=0; export AUDIT_SKIP_SEQ
    NEXT="auto-resumed session unusable — fresh session"
  fi
  [ -z "$NEXT" ] && break
  # Continuation rounds only get what is left of the single total budget.
  ROUND_LIMIT=$(( TIMEOUT_SECS - ($(date +%s) - RUN_START) ))
  if [ "$ROUND_LIMIT" -lt 60 ]; then
    echo ""
    echo "=== NO AUTO-CONTINUE: total time budget (${TIMEOUT_SECS}s) spent ==="
    break
  fi
  CONTINUED=$((CONTINUED + 1))
  ROUND=$((ROUND + 1))
  echo ""
  echo "=== AUTO-CONTINUE: $NEXT ==="
  CUR_PROMPT_FILE="$RUN_DIR/continue-prompt.txt"
  printf '%s' "You stopped before finishing (turn limit or a model API error). Continue the ORIGINAL task exactly where you stopped. Do not redo or re-read work that is already done; check the files you already changed only if you need to. RUN BUDGET: $MAX_TURNS more turns. Keep your last turn for a short final summary of everything you changed across the whole task." > "$CUR_PROMPT_FILE"
done
FINAL_OUTCOME="$R_OUTCOME"
FINAL_SID="$CUR_SID"

# Late-write rescan (2026-11-10). A limit stop (deadline / turn_limit) interrupts
# the model mid-turn and the pty wrapper's `timeout -k 15` lets the child finish
# its in-flight tool call briefly AFTER the stream EOF the parser saw — so a
# write_file can land on disk a few seconds after this loop ends, i.e. after the
# verdict's find -newer would have run. Settle, then let the CHANGED scan below
# (which runs after the token blocks) see it. Without this, the run is reported
# "0 file(s) changed" while the file exists on disk (observed: write journaled
# with a clean result, files_changed=0, the file on disk).
if [ "$FINAL_OUTCOME" = "deadline" ] || [ "$FINAL_OUTCOME" = "turn_limit" ] || [ "$FINAL_OUTCOME" = "terminated" ]; then
  sleep 5
fi

# Aggregate the exports of all rounds into the stats file (tokens are per round).
python3 - "$RUN_DIR" "$DELEGATE_STATS_FILE" "$CONTINUED" << 'PYAGG'
import glob, json, sys
run_dir, sf, continued = sys.argv[1], sys.argv[2], int(sys.argv[3])
exps = []
for p in sorted(glob.glob(run_dir + '/round-*/export.json'), key=lambda p: int(p.split('round-')[1].split('/')[0])):
    try:
        exps.append(json.load(open(p)))
    except (OSError, ValueError):
        pass
if not exps:
    sys.exit(0)
try:
    st = json.load(open(sf))
except (OSError, ValueError):
    st = {}
u_in = sum(((e.get('usage') or {}).get('input_tokens') or 0) for e in exps)
u_out = sum(((e.get('usage') or {}).get('output_tokens') or 0) for e in exps)
u_cached = sum(((e.get('usage') or {}).get('cached_input_tokens') or 0) for e in exps)
# Vibe's own cost is cache-aware (cached input billed at the provider's cached
# rate); None as soon as one round lacks it.
_costs = [e.get('cost_usd') for e in exps]
u_cost = round(sum(_costs), 6) if all(isinstance(c, (int, float)) for c in _costs) else None
last = exps[-1]
st.update({
    'vibe_outcome': last.get('outcome'),
    'vibe_stop_reason': last.get('stop_reason'),
    'vibe_error': ((last.get('error') or {}).get('message') or '')[:300],
    'vibe_steps': sum((e.get('steps') or 0) for e in exps),
    'vibe_rounds': len(exps),
    'auto_continued': continued,
    'round_outcomes': [e.get('outcome') for e in exps],
    'session_id': last.get('session_id'),
    'export_tokens_in': u_in,
    'export_tokens_out': u_out,
    'export_cached_in': u_cached,
    'export_cost_usd': u_cost,
})
json.dump(st, open(sf, 'w'))
PYAGG

# ── Real Mistral token counts from session log ─────────────────────────────────
VIBE_HOME="${VIBE_HOME:-$HOME/.vibe}"
# Only consider meta.json files written AFTER this run started (mtime newer than
# the pre-launch sentinel). Guards against inheriting a STALE session's tokens —
# happened on 2026-06-17 where a failed code-reviewer run silently inherited the
# prior run's 363,506 tokens — and narrows fan-out-vibe parallel cross-attribution
# to genuinely overlapping sessions.
# maxdepth 3: legacy layout is session_*/meta.json (depth 2); since ~2026-09 Vibe
# writes unified/<uuid>/meta.json (depth 3). With depth 2 only, every run was
# blind ("no session log", no journal recovery, no write audit).
# Pick OUR session, not merely the most recently touched one. 2026-10-07: a long-lived
# Vibe session of another project had its
# meta.json bumped during a run in another repo, was picked as "newest", and the
# verdict/WRITE AUDIT/token count then described the wrong project (FAILED [timeout]
# while the real session had 26 successful edits). A candidate must (1) have been
# started after this run began (start_time) and (2) belong to this workdir
# (origin_directory / environment.working_directory). Legacy meta.json without a
# directory is kept as a candidate.
SESSION_LOG=""
# Vibe 3: the export names the session exactly — no heuristic needed.
if [ -n "$FINAL_SID" ] && [ -f "$VIBE_HOME/logs/session/unified/$FINAL_SID/meta.json" ]; then
  SESSION_LOG="$VIBE_HOME/logs/session/unified/$FINAL_SID/meta.json"
fi
[ -z "$SESSION_LOG" ] && SESSION_LOG=$(find "$VIBE_HOME/logs/session" -mindepth 2 -maxdepth 3 -name meta.json -newer "$SENTINEL" 2>/dev/null \
  | RUN_WORKDIR="$WORKDIR" RUN_SENTINEL="$SENTINEL" python3 -c "
import sys, os, json, datetime
wd = os.path.realpath(os.environ['RUN_WORKDIR'])
t0 = os.path.getmtime(os.environ['RUN_SENTINEL']) - 10
best = None
for p in sys.stdin.read().split():
    try:
        m = json.load(open(p))
    except Exception:
        continue
    d = m.get('origin_directory') or (m.get('environment') or {}).get('working_directory') or ''
    if d and os.path.realpath(d) != wd:
        continue
    st = m.get('start_time')
    if st:
        try:
            if datetime.datetime.fromisoformat(st).timestamp() < t0:
                continue
        except Exception:
            pass
    mt = os.path.getmtime(p)
    if best is None or mt > best[0]:
        best = (mt, p)
print(best[1] if best else '')
")
if [ -z "$SESSION_LOG" ]; then
  echo "(no session log newer than run start — token count unknown, not reusing stale data)"
fi
if [ -n "$SESSION_LOG" ]; then
  python3 -c "
import json, sys, os
try:
    with open('$SESSION_LOG') as f:
        data = json.load(f)
    stats = data.get('stats') or {}  # unified meta.json carries no token stats
    prompt = stats.get('last_turn_prompt_tokens', 0)
    completion = stats.get('last_turn_completion_tokens', 0)
    total = stats.get('last_turn_total_tokens', prompt + completion)
    cost = stats.get('session_cost', 0)
    session_total = stats.get('session_total_llm_tokens', 0)
    # Exact cumulative in/out for the whole run — preferred over the last-turn ratio.
    session_in  = stats.get('session_prompt_tokens', 0)
    session_out = stats.get('session_completion_tokens', 0)
    model_name = (data.get('config') or {}).get('active_model', 'unknown')  # unified meta.json has "config": null
    turn_cap_hit = False
    if session_in == 0 and session_out == 0 and session_total == 0:
        try:
            sess_dir = os.path.dirname('$SESSION_LOG')
            with open(os.path.join(sess_dir, 'CURRENT')) as f:
                current_data = json.load(f)
            generation = current_data.get('generation', '')
            gen_dir = os.path.join(sess_dir, 'generations', generation)
            with open(os.path.join(gen_dir, 'projection-state.json')) as f:
                proj_data = json.load(f)
            usage = proj_data.get('snapshot', {}).get('session', {}).get('tokenUsage', {})
            session_in = usage.get('inputTokens', 0)
            session_out = usage.get('outputTokens', 0)
            with open(os.path.join(gen_dir, 'runtime-state.json')) as f:
                runtime_data = json.load(f)
            if runtime_data.get('session_metadata', {}).get('active_model'):
                model_name = runtime_data['session_metadata']['active_model']
            # --max-turns exhaustion is silent in Vibe 2.25 (exit 0, turn status
            # completed); the only trace is a final turn with no text output.
            # Verified 2026-10-01: max-turns 2 on a 6-file task, 1 file done.
            with open(os.path.join(gen_dir, 'checkpoint.json')) as f:
                outcome = (json.load(f).get('turn') or {}).get('outcome') or {}
            # Require BOTH: no final text AND model calls == the cap, so an empty
            # answer for any other reason is not mislabelled.
            completions = sum(1 for a in runtime_data.get('actions') or [] if a.get('kind') == 'completion')
            turn_cap_hit = (outcome.get('type') == 'completed' and not outcome.get('output')
                            and completions >= int('$MAX_TURNS' or 0) > 0)
        except Exception:
            pass
    # Vibe 3 export usage (summed over auto-continue rounds) is exact for THIS
    # run; the session totals above would also count an earlier --resume'd run.
    try:
        _ex = json.load(open(os.environ.get('DELEGATE_STATS_FILE', '')))
        if _ex.get('export_tokens_in') or _ex.get('export_tokens_out'):
            session_in, session_out = _ex['export_tokens_in'], _ex['export_tokens_out']
    except Exception:
        _ex = {}
    # Read per-model pricing from ~/.vibe/config.toml (fallback: Mistral Medium 3.5 rates)
    input_price, output_price = 1.5, 7.5
    try:
        import tomllib
    except ImportError:
        try:
            import tomli as tomllib
        except ImportError:
            tomllib = None
    if tomllib:
        config_path = os.path.expanduser('~/.vibe/config.toml')
        try:
            with open(config_path, 'rb') as cf:
                cfg = tomllib.load(cf)
            active = model_name  # use session's actual model, not config default
            for m in cfg.get('models', []):
                if m.get('alias') == active or m.get('name') == active:
                    input_price = m.get('input_price', input_price)
                    output_price = m.get('output_price', output_price)
                    break
        except Exception:
            pass

    # Each -p invocation creates a new session, so the session_* totals cover the
    # whole run. Prefer Vibe's exact cumulative in/out split; fall back to the
    # last-turn ratio only when the cumulative fields are absent (older Vibe).
    if session_in > 0 or session_out > 0:
        run_tokens_in, run_tokens_out = session_in, session_out
    else:
        run_total = session_total if session_total > 0 else total
        if (prompt + completion) > 0 and run_total > 0:
            ratio_in = prompt / (prompt + completion)
            run_tokens_in  = round(run_total * ratio_in)
            run_tokens_out = run_total - run_tokens_in
        else:
            run_tokens_in, run_tokens_out = prompt, completion
    run_total = run_tokens_in + run_tokens_out
    # Cache-aware since 2026-11-09. input_tokens INCLUDES cached_input_tokens
    # (Vibe 3 export). Most input is the conversation re-sent on every call and is
    # served from cache: pricing it all at the full rate overstated the cost about
    # 2x (one run: \$0.0289 cache-blind vs \$0.0154 billed by Vibe). Use Vibe's
    # own cost when it exported one. The Claude equivalent applies Claude's cache
    # read rate (\$0.30/M) to the same cached share; cache writes are ignored.
    cached_in = min(int(_ex.get('export_cached_in') or 0), run_tokens_in)
    uncached_in = run_tokens_in - cached_in
    if isinstance(_ex.get('export_cost_usd'), (int, float)):
        run_cost, cost_source = float(_ex['export_cost_usd']), 'vibe_export'
    else:
        run_cost = (run_tokens_in * input_price + run_tokens_out * output_price) / 1_000_000
        cost_source = 'list_price_no_cache'
    claude_cost = (uncached_in * 3.0 + cached_in * 0.30 + run_tokens_out * 15.0) / 1_000_000
    verbose = os.environ.get('DELEGATE_VERBOSE', '0') == '1'
    print(f'Model               : {model_name}')
    if verbose:
        in_cost  = run_tokens_in  * input_price  / 1_000_000
        out_cost = run_tokens_out * output_price / 1_000_000
        cl_in    = run_tokens_in  * 3.0  / 1_000_000
        cl_out   = run_tokens_out * 15.0 / 1_000_000
        print(f'  Input  : {run_tokens_in:>10,}  @ ${input_price:>5.2f}/M  = ${in_cost:.4f}')
        print(f'  Output : {run_tokens_out:>10,}  @ ${output_price:>5.2f}/M  = ${out_cost:.4f}')
        print(f'  Total  : {run_total:>10,}              = ${run_cost:.4f}')
        if run_cost > 0:
            print(f'  Claude : {run_total:>10,}  (@ $3/$15/M)  = ${claude_cost:.4f}  (x{claude_cost/run_cost:.1f} cheaper)')
        else:
            print(f'  Claude equiv            = ${claude_cost:.4f}')
    else:
        print(f'Delegate tokens (run): {run_total:,}  ({cached_in:,} of {run_tokens_in:,} input cached)  |  cost ~\${run_cost:.4f} ({cost_source})')
        if run_cost > 0:
            print(f'Claude Sonnet 4.6 eq: same tokens, same cache share ~\${claude_cost:.4f}  (ratio x{claude_cost/run_cost:.1f})')
        else:
            print(f'Claude Sonnet 4.6 eq: ~\${claude_cost:.4f}')
    # Merge token stats into the delegate stats file.
    sf = os.environ.get('DELEGATE_STATS_FILE', '')
    if sf:
        try:
            existing = json.load(open(sf))
        except Exception:
            existing = {}
        existing.update({
            'tokens_in':    run_tokens_in,
            'tokens_out':   run_tokens_out,
            'tokens_total': run_total,
            'cost_usd':     round(run_cost, 6),
            'cost_source':  cost_source,
            'tokens_cached_in': cached_in,
            'cost_claude_eq': round(claude_cost, 6),
            'model':        model_name,
            'turn_cap_hit': turn_cap_hit,
        })
        with open(sf, 'w') as wf:
            json.dump(existing, wf)
except Exception as e:
    print(f'(token read failed: {e})')
" 2>/dev/null
fi

# Full final answer (H6). The stream parser cuts every [vibe] line at 400 chars,
# so the supervisor never saw Vibe's own summary. Vibe 3 has no turn outcome in
# checkpoint.json (the block was always empty since 2026-10-29): the answer is
# the text of the last model completion in the journal. Round copies are read
# too, because the live journal is pruned on every resume.
if [ -n "$SESSION_LOG" ]; then
  AUDIT_RUN_DIR="$RUN_DIR" FINAL_ANSWER_FILE="$RUN_DIR/final-answer.txt" python3 - "$(dirname "$SESSION_LOG")" << 'PYANSWER'
import glob, json, os, re, sys
sess = sys.argv[1]
files = sorted(glob.glob(sess + "/journal/*.jsonl"))
rd = os.environ.get("AUDIT_RUN_DIR", "")
if rd:
    files += sorted(glob.glob(rd + "/round-*/session/journal/*.jsonl"))
skip = int(os.environ.get("AUDIT_SKIP_SEQ", "0") or 0)
best = (-1, "")
for f in files:
    for line in open(f, errors="replace"):
        try:
            e = json.loads(line)
        except ValueError:
            continue
        if not isinstance(e, dict) or e.get("type") != "action_result":
            continue
        seq = e.get("sequence") or 0
        if seq <= skip or seq <= best[0]:
            continue
        r = ((e.get("payload") or {}).get("result") or {}).get("result")
        if not isinstance(r, dict) or "finish_reason" not in r:
            continue
        text = "\n".join(p.get("text", "") for p in r.get("parts") or []
                         if isinstance(p, dict) and p.get("type") == "text").strip()
        if text:
            best = (seq, text)
# Same control-char stripping as the stream parser: this text reaches a terminal
# and the orchestrating model.
text = re.sub(r"\x1b\[[0-9;]*[A-Za-z]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", best[1])
_fa_path = os.environ.get("FINAL_ANSWER_FILE", "")
if _fa_path:
    try:
        with open(_fa_path, "w") as _fa_fh:
            _fa_fh.write(text)
    except OSError:
        pass
print("")
print("=== VIBE FINAL ANSWER (full, last model message from the session journal) ===")
print(text if text else "(none — Vibe stopped before writing a final message; see RESULT below)")
PYANSWER
fi

echo ""
if [ "$VIBE_EXIT" -eq 124 ]; then
  echo "=== VIBE KILLED by backstop (>${BACKSTOP_SECS}s, Vibe ignored its own --time-limit) ==="
else
  echo "=== VIBE DONE (exit: $VIBE_EXIT, outcome: ${FINAL_OUTCOME:-unknown}, rounds:${OUTCOMES}) ==="
fi

# ── Post-run syntax checks — language-agnostic ────────────────────────────────
# CWD is $WORKDIR (cd happened before launch). Anything with an mtime newer than
# the sentinel was actually written during this run — true regardless of whether
# the file was tracked, untracked, already dirty, or this is a non-git directory.
# Caches created by Vibe's own test runs (__pycache__, .pytest_cache...) are not
# changes: they inflated "N file(s) changed" (2 real edits reported as 6).
CHANGED=$(find . \( -name .git -o -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name .ruff_cache -o -name node_modules -o -name .vibe-recovery \) -prune -o -type f -newer "$SENTINEL" -print 2>/dev/null | sed 's|^\./||')

SYNTAX_COUNT_FILE=$(mktemp /tmp/vibe-syntax-count-XXXXXX.txt)
echo 0 > "$SYNTAX_COUNT_FILE"
export DELEGATE_CHANGED="$CHANGED"
export SYNTAX_COUNT_FILE

python3 << 'PYSYNTAX'
import os, shutil, subprocess

changed = [f for f in os.environ.get('DELEGATE_CHANGED', '').splitlines() if f.strip()]
# CWD is always $WORKDIR — cd "$WORKDIR" runs before this block.
errors  = 0
checked = 0

def has(cmd):
    return shutil.which(cmd) is not None

def check(cmd, label, cwd=None):
    global errors, checked
    r = subprocess.run(cmd, capture_output=True, text=True, cwd=cwd)
    checked += 1
    if r.returncode != 0:
        errors += 1
        msg = (r.stderr or r.stdout).strip().split('\n')[0][:120]
        print(f'  [SYNTAX ERROR] {label}: {msg}')

# Per-file checks — tools available without project context
for f in changed:
    if not os.path.isfile(f):
        continue
    if   f.endswith('.py'):
        # compile() in-process: `py_compile` wrote __pycache__/ into the user's repo.
        check(['python3', '-c', 'import sys;compile(open(sys.argv[1],encoding="utf-8").read(),sys.argv[1],"exec")', f], f)
    elif f.endswith(('.js', '.mjs', '.cjs')) and has('node'):
        check(['node', '--check', f], f)
    elif f.endswith('.rb') and has('ruby'):
        check(['ruby', '-c', f], f)
    elif f.endswith(('.sh', '.bash')):
        check(['bash', '-n', f], f)
    elif f.endswith('.php') and has('php'):
        check(['php', '-l', f], f)
    elif f.endswith('.json'):
        check(['python3', '-c', 'import json,sys;json.load(open(sys.argv[1]))', f], f)

# Project-level checks — run once if any matching files changed
live = [f for f in changed if os.path.isfile(f)]
if any(f.endswith('.go') for f in live) and has('go'):
    check(['go', 'vet', './...'], 'go vet')
if any(f.endswith('.rs') for f in live) and has('cargo'):
    check(['cargo', 'check', '--quiet'], 'cargo check')
if any(f.endswith(('.ts', '.tsx')) for f in live):
    if has('tsc') and os.path.isfile('tsconfig.json'):
        check(['tsc', '--noEmit', '--skipLibCheck'], 'tsc --noEmit')
    else:
        print('  [SKIP] tsc — no tsconfig.json found, TypeScript not checked')

if checked > 0:
    if errors == 0:
        print(f'=== SYNTAX OK ({checked} check(s)) ===')
    else:
        print(f'=== SYNTAX ERRORS: {errors} in {checked} check(s) — fix before committing ===')

cf = os.environ.get('SYNTAX_COUNT_FILE', '')
if cf:
    with open(cf, 'w') as fh:
        fh.write(str(errors))
PYSYNTAX

TOTAL_ERRORS=$(cat "$SYNTAX_COUNT_FILE" 2>/dev/null || echo 0)
rm -f "$SYNTAX_COUNT_FILE"

# ── Git summary ────────────────────────────────────────────────────────────────
GIT_AFTER=$(git rev-parse HEAD 2>/dev/null || echo "no-git")

# ── Write audit: what Vibe journaled vs what actually changed on disk ─────────
# The session journal is the ground truth of every write attempt. Vibe 3 layout
# (verified 2026-11-09 on 3.0.3): <session>/journal/<first-seq>.jsonl, one record
# per line {sequence, type, payload}. A tool call is an `action_intent` record
# (payload.kind == "tool", payload.request.call = {name, arguments}) and its
# outcome the `action_result` record with the same action_id (result.result.error
# set on failure, e.g. tool_denied). Write tools: file_system.edit /
# search_replace / write_file; target in arguments.file_path or .path.
# The previous audit read a pre-Vibe-3 shape (toolName/input) and the pruned
# runtime-state, so on Vibe 3 it saw 0 writes on every run.
if [ -n "$SESSION_LOG" ] && [ -d "$(dirname "$SESSION_LOG")/journal" ]; then
  CHANGED_LIST="$CHANGED" AUDIT_RUN_DIR="$RUN_DIR" AUDIT_FINAL_OUTCOME="$FINAL_OUTCOME" python3 - "$(dirname "$SESSION_LOG")" << 'PYAUDIT' || AUDIT_RC=$?
import glob, json, os, re, sys

sess = sys.argv[1]
changed = {p.strip() for p in os.environ.get("CHANGED_LIST", "").split() if p.strip()}
# A --resume'd session's journal also holds earlier runs' writes: skip them.
skip = int(os.environ.get("AUDIT_SKIP_SEQ", "0") or 0)
WRITE_TOOLS = {"edit", "search_replace", "write_file"}

def rel(path):
    path = path or ""
    return os.path.relpath(path) if os.path.isabs(path) else os.path.normpath(path)

intents, results, order, intent_args = {}, {}, [], {}
# Vibe prunes the live journal when it snapshots a new generation (every resume,
# so every auto-continue round): round 1 wrote a-d, the live journal then held
# only round 2 (seen 2026-11-09). Each round's --output-dir keeps a full copy of
# the journal as of that round's end, so read those too; action_id dedups.
journal_files = sorted(glob.glob(sess + "/journal/*.jsonl"))
run_dir = os.environ.get("AUDIT_RUN_DIR", "")
if run_dir:
    journal_files += sorted(glob.glob(run_dir + "/round-*/session/journal/*.jsonl"))
for f in journal_files:
    for line in open(f, errors="replace"):
        try:
            e = json.loads(line)
        except ValueError:
            continue
        if not isinstance(e, dict) or (e.get("sequence") or 0) <= skip:
            continue
        p = e.get("payload") or {}
        if not isinstance(p, dict):
            continue
        aid = p.get("action_id")
        if e.get("type") == "action_intent" and p.get("kind") == "tool":
            call = (p.get("request") or {}).get("call") or {}
            tool = str(call.get("name") or "").split(".")[-1]
            if tool in WRITE_TOOLS and aid not in intents:
                args = call.get("arguments") or {}
                body = args.get("content") if tool == "write_file" else args.get("new_string")
                intents[aid] = (tool, rel(args.get("file_path") or args.get("path")),
                                len(body) if isinstance(body, str) else 0)
                intent_args[aid] = args
                order.append(aid)
        elif e.get("type") == "action_result" and aid:
            r = (p.get("result") or {}).get("result")
            if isinstance(r, dict):
                err = r.get("error") or {}
                results[aid] = (not err, (err.get("message") or "") if isinstance(err, dict) else str(err))

print("")
print("=== WRITE AUDIT (journal vs disk) ===")
mismatch = False
calls = []
for aid in order:
    tool, path, size = intents[aid]
    ok, err = results.get(aid, (False, "no result recorded (run stopped mid-call?)"))
    calls.append((tool, path, ok, err))
if not calls:
    print("  journal: 0 write calls (Vibe only read/explored, or wrote via bash)")
outside = set()
for tool, path, ok, err in calls:
    if path.startswith(".."):
        outside.add(path)
        print(f"  {tool:<14} {path}  call: {'ok' if ok else 'FAILED'}  (outside workdir, not checked)")
        continue
    disk = "CHANGED" if path in changed else "UNCHANGED"
    flag = "  <-- MISMATCH" if ok and path not in changed else ""
    mismatch = mismatch or bool(flag)
    state = "ok" if ok else f"FAILED ({err[:90]})"
    print(f"  {tool:<14} {path}  call: {state}  disk: {disk}{flag}")
ok_paths = {p for _, p, ok, _ in calls if ok}
failed_paths = {p for _, p, ok, _ in calls if not ok}
unrecovered = len(failed_paths - ok_paths)
if failed_paths and not unrecovered:
    print("  (every failed write was followed by a successful one on the same file — recovered)")
for p in sorted(changed - {p for _, p, _, _ in calls}):
    print(f"  [note] {p} changed on disk without a write call (bash/run_typescript, or a generated file)")

# Orphaned-write recovery (2026-11-10): on a limit stop (deadline / turn_limit /
# terminated) a write intent can have no action_result — the run was cut
# mid-call and the payload never reached disk. Save every such payload under
# .vibe-recovery/ in the workdir, NOT applied — a human/Claude applies it after
# reading the audit. Without this the content existed only in a pruned journal.
outcome = os.environ.get("AUDIT_FINAL_OUTCOME", "")
if outcome in ("deadline", "turn_limit", "terminated"):
    orphans = [(aid, intents[aid][0], intents[aid][1]) for aid in order
               if aid in intent_args and aid not in results and not intents[aid][1].startswith("..")]
    if orphans:
        rec_dir = os.path.join(os.getcwd(), ".vibe-recovery")
        os.makedirs(rec_dir, exist_ok=True)
        print("")
        print("=== ORPHANED WRITE RECOVERY (run cut mid-call; payloads saved, NOT applied) ===")
        for aid, tool, path in orphans:
            safe = re.sub(r"[^A-Za-z0-9_.-]", "_", path.strip("/"))[:120]
            out = os.path.join(rec_dir, safe + ".json")
            with open(out, "w") as fh:
                json.dump({"tool": tool, "file_path": path, "arguments": intent_args[aid]}, fh, indent=1)
            print(f"  {tool:<14} {path}  -> {out}")
sf = os.environ.get("DELEGATE_STATS_FILE", "")
if sf:
    try:
        st = json.load(open(sf))
        st["sr_unrecovered"] = unrecovered
        st["audit_write_calls"] = len(calls)
        json.dump(st, open(sf, "w"))
    except (OSError, ValueError):
        pass
# exit 9 = a successful write call did not land on disk (surfaced as RESULT: FAILED)
sys.exit(9 if mismatch else 0)
PYAUDIT
  if [ "${AUDIT_RC:-0}" = "9" ]; then export DELEGATE_AUDIT_MISMATCH=1; fi
fi

if [ "$GIT_BEFORE" != "$GIT_AFTER" ]; then
  echo ""
  echo "=== COMMITS CREATED ==="
  git log "$GIT_BEFORE".."$GIT_AFTER" --oneline
  echo ""
  echo "=== DIFF STAT ==="
  git diff "$GIT_BEFORE".."$GIT_AFTER" --stat
else
  echo ""
  echo "=== UNCOMMITTED CHANGES ==="
  git diff --stat -- "$WORKDIR" 2>/dev/null || echo "(no git)"
  git status --short -- "$WORKDIR" 2>/dev/null
fi

# Compact diff of the files THIS run changed (2026-11-10). Claude must re-read
# Vibe's work; separate grep / Read / git diff calls cost it 4 follow-up turns in
# the median real delegation, each re-reading a ~216k-token context. Printing the
# diff here lets it review in the same turn. Capped at DELEGATE_DIFF_LINES (150).
if [ -n "$(printf '%s' "$CHANGED" | tr -d '[:space:]')" ] && git rev-parse --git-dir >/dev/null 2>&1; then
  CHANGED_LIST="$CHANGED" python3 - << 'PYDIFF'
import os, subprocess
cap = int(os.environ.get("DELEGATE_DIFF_LINES", "150") or 150)
files = [f for f in os.environ.get("CHANGED_LIST", "").split() if f.strip()]
out = []
for f in files:
    tracked = subprocess.run(["git", "ls-files", "--error-unmatch", f], capture_output=True).returncode == 0
    if tracked:
        d = subprocess.run(["git", "diff", "-U1", "--no-color", "--", f], capture_output=True, text=True).stdout
        out += [l for l in d.splitlines() if not l.startswith(("diff --git", "index "))]
    else:
        try:
            lines = open(f, errors="replace").read().splitlines()
        except OSError:
            continue
        out.append(f"+++ new file {f} ({len(lines)} lines)")
        out += ["+" + l for l in lines]
total = len(out)
print("")
print(f"=== DIFF (this run, {len(files)} file(s), {total} lines) ===")
print("\n".join(out[:cap]))
if total > cap:
    print(f"... truncated at {cap} of {total} lines: read the rest with git diff only where needed")
PYDIFF
fi


# ── Run log ────────────────────────────────────────────────────────────────────
END_NS=$(date +%s%N)
FILES_CHANGED_COUNT=$(printf '%s\n' "$CHANGED" | grep -c '[^[:space:]]' 2>/dev/null)
FILES_CHANGED_COUNT=${FILES_CHANGED_COUNT:-0}
TOTAL_ERRORS=${TOTAL_ERRORS:-0}

[ -n "$SESSION_LOG" ] && export DELEGATE_HAD_SESSION=1
[ -n "$RESUME_SESSION" ] && export DELEGATE_RESUMED=1
export DELEGATE_NAME="vibe"
export DELEGATE_WORKDIR="$WORKDIR"
export DELEGATE_EXIT="$VIBE_EXIT"
export DELEGATE_TIMEOUT="$TIMEOUT_SECS"
export DELEGATE_PROMPT_WORDS="$PROMPT_WORDS"
export DELEGATE_AGENT="${AGENT:-auto-approve}"
export DELEGATE_MAX_TURNS="$MAX_TURNS"
export DELEGATE_FILES_CHANGED="$FILES_CHANGED_COUNT"
export DELEGATE_SYNTAX_ERRORS="$TOTAL_ERRORS"
export DELEGATE_START_NS="$START_NS"
export DELEGATE_END_NS="$END_NS"
export DELEGATE_PROMPT_FILE="$PROMPT_FILE"
export DELEGATE_RESUMED_SESSION="${RESUME_SESSION:-}"
export DELEGATE_RESUME_MODE="${RESUME_MODE:-}"
export DELEGATE_FINAL_ANSWER_FILE="$RUN_DIR/final-answer.txt"
export DELEGATE_CHANGED_LIST="$CHANGED"
export DELEGATE_GIT_BEFORE="$GIT_BEFORE"
export DELEGATE_SENTINEL="$SENTINEL"

python3 << 'PYLOG'
import json, os, re
from pathlib import Path
from datetime import datetime, timezone

LOG = Path(os.environ.get('DELEGATE_RUN_LOG') or Path.home() / '.local' / 'share' / 'delegate-runs.jsonl')
LOG.parent.mkdir(parents=True, exist_ok=True)

sf = os.environ.get('DELEGATE_STATS_FILE', '')
stats = {}
if sf:
    try:
        stats = json.loads(Path(sf).read_text())
    except Exception:
        pass

start_ns = int(os.environ.get('DELEGATE_START_NS', 0) or 0)
end_ns   = int(os.environ.get('DELEGATE_END_NS',   0) or 0)
duration = round((end_ns - start_ns) / 1e9, 1) if start_ns and end_ns else 0

# Detect prompt adaptations from the prompt text.
# These are logged per-run so failure rates can be compared across adaptation styles.
prompt_text = ''
pf = os.environ.get('DELEGATE_PROMPT_FILE', '')
if pf:
    try:
        prompt_text = Path(pf).read_text(errors='replace')
    except Exception:
        pass

adaptations = []
if prompt_text:
    # contract: prompt includes a Python function signature or return type annotation
    if re.search(r'\bdef \w+\s*\(|->|\bCallable\b|: \w+\[', prompt_text):
        adaptations.append('contract')
    # output_format: prompt requests a structured receipt (Modified:/Does:/OUTPUT FORMAT)
    if re.search(r'OUTPUT\s+FORMAT|Modified:|Created/Modified:|Does:', prompt_text, re.I):
        adaptations.append('output_format')
    # compact: short, focused prompt (fewer context tokens on the delegate side)
    if len(prompt_text.split()) < 80:
        adaptations.append('compact')

entry = {
    'ts':            datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
    'delegate':      os.environ.get('DELEGATE_NAME', 'vibe'),
    # Head of the final prompt, kept so a future auto-resume heuristic could be
    # calibrated by replaying the log (similarity auto-resume removed 2026-11-10).
    'prompt_head':   (prompt_text or '')[:1500],
    'workdir':       os.environ.get('DELEGATE_WORKDIR', ''),
    'project':       os.path.basename(os.environ.get('DELEGATE_WORKDIR', '')),
    'prompt_words':  int(os.environ.get('DELEGATE_PROMPT_WORDS', 0) or 0),
    'agent':         os.environ.get('DELEGATE_AGENT', 'default'),
    'max_turns':     int(os.environ.get('DELEGATE_MAX_TURNS', 0) or 0),
    'timeout_secs':  int(os.environ.get('DELEGATE_TIMEOUT', 0) or 0),
    'exit_code':     int(os.environ.get('DELEGATE_EXIT', 0) or 0),
    'timed_out':     os.environ.get('DELEGATE_EXIT') == '124',
    'files_changed':        int(os.environ.get('DELEGATE_FILES_CHANGED', 0) or 0),
    'syntax_errors':        int(os.environ.get('DELEGATE_SYNTAX_ERRORS', 0) or 0),
    'duration_secs':        duration,
    'warn_count':           stats.get('warn_count', 0),
    'search_replace_fails': stats.get('search_replace_fails', 0),
    'adaptations':          adaptations,
    # Rules bypassed by --force at the launch preflight ('' when none refused).
    'preflight_forced':     os.environ.get('DELEGATE_PREFLIGHT_FORCED', ''),
}
entry.update(stats)

# Resume provenance: lets delegate-report measure auto-resume usage and
# resume-chain length per workdir. prompt_head stays logged so a future
# auto-resume heuristic could be calibrated by replaying the log.
if os.environ.get('DELEGATE_RESUMED_SESSION'):
    entry['resumed_session'] = os.environ['DELEGATE_RESUMED_SESSION']
    entry['resume_mode'] = os.environ.get('DELEGATE_RESUME_MODE') or 'explicit'

# Compute Claude Sonnet 4.6 equivalent cost for savings tracking.
ti = entry.get('tokens_in', 0)
to = entry.get('tokens_out', 0)
if not isinstance(entry.get('cost_claude_eq'), (int, float)):
    entry['cost_claude_eq'] = round((ti * 3.0 + to * 15.0) / 1_000_000, 6)

# failure_reason: specific classification of run outcome (more precise than wrote_nothing).
# silent_exit   — vibe never engaged: 0 tokens, 0 tool calls (immediate exit or auth failure)
# near_empty    — minimal output (<50 tokens), nothing written (scaffold header only)
# wrote_nothing — had tool calls but wrote no files (prompt too vague or task already done)
# timeout / exit_error / syntax_error / sr_fail — other failure modes
# warn_only     — completed with non-fatal warnings
# ok            — clean run
# Agents that legitimately produce no file writes, so "wrote nothing" is the
# expected outcome and not a failure. 'plan' / 'explore' are the current Vibe
# built-ins; the last three names are kept for older installs where they
# existed as custom agents (a name that is simply absent here just means a
# read-only run gets flagged wrote_nothing, which is what happened to every
# `plan` review before 2026-08-02). 'chat' is deliberately NOT here: it is
# absent from BUILTIN_AGENTS in 2.22.0 and dropped from the enum in 2.24.0,
# so --agent chat never reaches this code at all.
_readonly_agents = ('plan', 'explore', 'readonly', 'code-reviewer', 'code-architect', 'code-explorer', 'planner', 'architect')
_tok_out  = entry.get('tokens_out', 0) or 0
_tc       = entry.get('tool_calls', 0) or 0
_fc       = entry.get('files_changed', 0) or 0
_exit     = entry.get('exit_code', 0)
_agent    = entry.get('agent', 'default')
# Vibe 3 export outcome: the run's own account of how it ended (run_export.py
# RunOutcome). Before 2026-11-09 every non-zero exit was logged 'exit_error',
# so "out of turns" (exit 3), "API down" (exit 2) and "bad flag" (exit 1) all
# read as a crash.
_vo       = stats.get('vibe_outcome') or ''

if entry.get('timed_out'):
    _reason = 'timeout'
elif _vo in ('deadline', 'terminated'):
    _reason = 'timeout'
elif _vo == 'turn_limit':
    _reason = 'turn_cap'
elif _vo in ('token_limit', 'price_limit', 'length'):
    _reason = 'budget_limit'
elif _vo == 'refusal':
    _reason = 'refusal'
elif _vo == 'infrastructure_failure':
    # 0 steps = Vibe never ran the agent: a bad agent name/flag/config, not the API.
    # A 4xx (not 429) is the provider refusing the request itself: config, not transient.
    _err = stats.get('vibe_error') or ''
    _perm = bool(re.search(r'Status 4\d\d', _err)) and 'Status 429' not in _err
    _reason = 'infra_error' if stats.get('vibe_steps') and not _perm else 'usage_error'
elif _vo in ('usage_error', 'config_error'):
    _reason = 'usage_error'
elif _exit not in (0, 124):
    # A sandbox "Tool execution not permitted" message inflates exit to 1 even when
    # the files were actually written (seen 2026-06-17, run with fc=2 still logged
    # exit_error). Don't let that mask a real success.
    if stats.get('sandbox_blocked') and _fc > 0:
        _reason = 'sandbox_blocked_ok'
    else:
        _reason = 'exit_error'
elif entry.get('syntax_errors', 0) > 0:
    _reason = 'syntax_error'
elif stats.get('sr_unrecovered', entry.get('search_replace_fails', 0)) > 0:
    # Only an edit failure with no later successful edit on the same file counts
    # (H5). A recovered failure falls through to warn_only.
    _reason = 'sr_fail'
elif stats.get('denied_count') and _fc == 0:
    # Denials were counted but never classified: a fully-denied run wrote no
    # files, so it fell through to wrote_nothing/silent_exit and triggered the
    # retry-then-ghostwrite ladder — retrying a run the sandbox will deny again.
    # Deliberately NOT added to the wrote_nothing tuple below.
    _reason = 'denied'
elif _fc == 0 and _vo == 'finished' and os.environ.get('DELEGATE_RESUMED') == '1':
    # A resumed session that finishes without writing: the earlier run already
    # did the work (seen 2026-11-09: 4/4 files written, then turn_limit before
    # the summary). Not a failure; the final answer above says what is left.
    _reason = 'ok_resumed_nothing_left'
elif _tc == 0 and _fc == 0 and _agent not in _readonly_agents:
    # Zero tool calls always means nothing was written, regardless of how much text
    # came back. Previously this only fired when tok_out was ALSO 0, which is exactly
    # how the mistral-medium "narrate the file instead of calling write_file" failure
    # (observed 2026-06-17 — tc=0, fc=0, but tok_out large) got logged as 'ok'.
    _reason = 'narrated_no_tools' if _tok_out > 0 else 'silent_exit'
elif _tok_out < 50 and _fc == 0 and _tc < 3 and _agent not in _readonly_agents:
    _reason = 'near_empty'
elif _fc == 0 and _exit == 0 and _agent not in _readonly_agents:
    # No `_tc >= 3` floor (removed 2026-09-30): a write-capable run that changed
    # no file is never "ok", whether it made 1 tool call or 8. With the floor, a
    # 1-2 call run with prose output fell through to 'ok'.
    _reason = 'wrote_nothing'
elif os.environ.get('DELEGATE_AUDIT_MISMATCH') and _agent not in _readonly_agents:
    # A write the journal recorded never reached disk (see WRITE AUDIT above).
    _reason = 'write_mismatch'
elif stats.get('turn_cap_hit') and not _vo and _agent not in _readonly_agents:
    # Legacy heuristic, only when there is no Vibe 3 export to say 'finished'.
    # Files changed, but Vibe ran out of turns before its final answer: the
    # task is likely PARTIAL. Before this check such runs were logged as 'ok'.
    _reason = 'turn_cap'
elif entry.get('warn_count', 0) > 0:
    _reason = 'warn_only'
else:
    _reason = 'ok'

entry['failure_reason'] = _reason
# wrote_nothing kept for backwards compat with older delegate-report versions
entry['wrote_nothing'] = _reason in ('wrote_nothing', 'silent_exit', 'near_empty')

# ── Ground-truth delegation report ─────────────────────────────────────────────
# Best-effort block: every subprocess / file call is guarded, so a report
# problem can never break the log write or the RESULT line below. The cwd of
# this process is already the workdir.
import os as _os, re as _re, subprocess as _sp, shutil as _sh
_report, _contras, _missing, _undeclared = [], [], [], []
_written, _vibe_vals = [], {}
_vibe_report_present = False
_sid_rep = ''
try:
    _sid_rep = stats.get('session_id') or ''
except Exception:
    pass
_limit_reasons = ('turn_cap', 'timeout', 'budget_limit', 'infra_error')
_fail_reasons = {'wrote_nothing', 'silent_exit', 'near_empty', 'narrated_no_tools',
                 'denied', 'write_mismatch', 'syntax_error', 'sr_fail', 'exit_error',
                 'turn_cap', 'timeout', 'budget_limit', 'refusal', 'infra_error',
                 'usage_error'}
try:
    _ro = _agent in _readonly_agents
except Exception:
    _ro = False

# STATUS: the same verdict word the RESULT line below will print.
if _reason in _limit_reasons and _fc > 0:
    _verdict = 'PARTIAL'
elif _reason in _fail_reasons:
    _verdict = 'FAILED'
elif _ro:
    _verdict = 'READ-ONLY'
else:
    _verdict = 'OK'
_report.append(f'STATUS: {_verdict} [{_reason}]')

# FILES: what actually landed, cross-checked against the declared MODIFY set.
try:
    _written = [w for w in (_os.environ.get('DELEGATE_CHANGED_LIST') or '').split() if w]
    if _ro:
        _report.append('FILES: n/a (read-only)')
    elif not _written:
        _report.append('FILES: none written')
    else:
        _base = (_os.environ.get('DELEGATE_GIT_BEFORE') or '').strip()
        if _base in ('', 'no-git'):
            _base = 'HEAD'
        _numstat = {}
        try:
            # --relative: paths relative to the workdir (= cwd), like CHANGED,
            # even when the workdir is a subdirectory of the repo.
            _ns = _sp.run(['git', 'diff', '--numstat', '--relative', _base],
                          capture_output=True, text=True, timeout=30)
            for _ln in (_ns.stdout or '').splitlines():
                _parts = _ln.split('\t')
                if len(_parts) == 3:
                    _numstat[_parts[2]] = (_parts[0], _parts[1])
        except Exception:
            _numstat = {}
        _shown = []
        for _wf in _written:
            if _wf in _numstat:
                _shown.append(f'+{_numstat[_wf][0]} -{_numstat[_wf][1]} {_wf}')
            else:
                try:
                    with open(_wf, errors='replace') as _fh:
                        _nlines = sum(1 for _ in _fh)
                except Exception:
                    _nlines = 0
                _shown.append(f'new {_wf} ({_nlines} lines)')
        if len(_shown) > 6:
            _report.append('FILES: ' + ', '.join(_shown[:6]) + f' (+{len(_shown) - 6} more)')
        else:
            _report.append('FILES: ' + ', '.join(_shown))
except Exception:
    pass
# Declared vs written: also on a run that wrote nothing (every declared file is
# then missing) — that is the case the check exists for.
_declared = []
try:
    for _dl in (_os.environ.get('DELEGATE_MODIFY_FILES') or '').split('\n'):
        _dl = _dl.strip()
        if not _dl:
            continue
        if _dl.startswith('./'):
            _dl = _dl[2:]
        if _os.path.isabs(_dl):
            try:
                _dl = _os.path.relpath(_dl, _os.getcwd())
            except ValueError:
                pass
        _declared.append(_dl)
    if not _ro:
        _missing = sorted(set(_declared) - set(_written))
        _undeclared = sorted(set(_written) - set(_declared)) if _declared else []
        if _missing:
            _report.append('  declared, not written: ' + ', '.join(_missing))
        if _undeclared:
            _report.append('  written, not declared: ' + ', '.join(_undeclared))
except Exception:
    pass

# RUN: the run's own accounting, from the journalled stats, not from narration.
try:
    if _os.environ.get('DELEGATE_RESUMED_SESSION'):
        _run_mode = 'resumed (' + (_os.environ.get('DELEGATE_RESUME_MODE') or '') + ')'
    else:
        _run_mode = 'fresh'
    _report.append(f"RUN: turns {stats.get('vibe_steps')}, {duration}s, "
                  f"${entry.get('cost_usd', 0):.4f}, session {_sid_rep or 'none'}, {_run_mode}")
except Exception:
    pass

# VIBE: the five END REPORT labels the harness asked Vibe to end with.
try:
    _fa = _os.environ.get('DELEGATE_FINAL_ANSWER_FILE') or ''
    if _fa and _os.path.exists(_fa):
        _lab_re = _re.compile(r'^(NOT DONE|DONE|ASSUMED|BLOCKED|CHECK)\*{0,2}\s*:\s*(.*)$')
        with open(_fa, errors='replace') as _fh:
            for _raw in _fh:
                _l = _raw.strip().lstrip('-*#').strip()
                if not _l:
                    continue
                _m = _lab_re.match(_l)
                if _m and _m.group(1) not in _vibe_vals:
                    _vibe_vals[_m.group(1)] = _m.group(2).strip().strip('*').strip()
    if _vibe_vals:
        _vibe_report_present = True
        _report.append('VIBE:')
        for _lab in ('NOT DONE', 'DONE', 'ASSUMED', 'BLOCKED', 'CHECK'):
            if _lab in _vibe_vals:
                _report.append(f'  {_lab}: {_vibe_vals[_lab][:150]}')
    else:
        _report.append('VIBE: Vibe report absent (run cut?)')
except Exception:
    pass

# CONTRADICTION: Vibe's claims checked against the disk.
try:
    if _vibe_vals.get('DONE'):
        # Exact cwd-relative paths changed vs HEAD or untracked (an earlier run
        # of a resumed task may have written the file), not a substring match.
        _dirty = set()
        for _cmd in (['git', 'diff', '--name-only', '--relative', 'HEAD'],
                     ['git', 'ls-files', '--others', '--exclude-standard']):
            try:
                _dirty.update(_sp.run(_cmd, capture_output=True, text=True,
                                      timeout=30).stdout.split())
            except Exception:
                pass
        # Only tokens that name a file: a declared path, or a known extension
        # (not foo.bar() calls, versions or "e.g").
        _ext_re = _re.compile(r'\.(py|js|ts|jsx|tsx|html|json|md|sh|css|ya?ml|toml|txt|csv|go|rs|rb|java|c|h|cpp|sql)$')
        for _tok in sorted(set(_re.findall(r'[A-Za-z0-9_./-]+\.[A-Za-z0-9_-]+', _vibe_vals['DONE']))):
            _tok = _tok[2:] if _tok.startswith('./') else _tok
            if not (_tok in _declared or _ext_re.search(_tok)):
                continue
            if _tok not in _written and _tok not in _dirty:
                _contras.append(f'CONTRADICTION: Vibe says DONE on {_tok}, but it was not written')
    _report.extend(_contras)
except Exception:
    pass

# RECOVER: payloads written into .vibe-recovery/ after the sentinel was created.
try:
    _recs = []
    _sent = _os.environ.get('DELEGATE_SENTINEL') or ''
    _sent_m = None
    if _sent:
        try:
            _sent_m = _os.path.getmtime(_sent)
        except OSError:
            _sent_m = None
    if _sent_m is not None and _os.path.isdir('.vibe-recovery'):
        for _rn in sorted(_os.listdir('.vibe-recovery')):
            _rp = _os.path.join('.vibe-recovery', _rn)
            try:
                if _os.path.isfile(_rp) and _os.path.getmtime(_rp) > _sent_m:
                    _recs.append(_rn)
            except OSError:
                pass
    if _recs:
        _report.append(f'RECOVER: {len(_recs)} payload(s) in .vibe-recovery/: '
                       + ', '.join(_recs[:3]))
    else:
        _report.append('RECOVER: none')
except Exception:
    pass

# NEXT: what the caller should do with this run.
try:
    if _reason in _limit_reasons and _sid_rep:
        _report.append(f'NEXT: vibe-delegate {_os.getcwd()} "continue" '
                       f'{_os.environ.get("DELEGATE_MAX_TURNS", "")} --resume {_sid_rep}')
    elif _contras:
        _report.append('NEXT: resolve the CONTRADICTION line(s) before accepting the run')
    elif _verdict in ('OK', 'READ-ONLY'):
        _report.append('NEXT: none')
    else:
        _report.append('NEXT: fix the cause named in RESULT; do not relaunch verbatim')
except Exception:
    pass

entry['report_files_undeclared'] = _undeclared
entry['report_files_missing'] = _missing
entry['vibe_report_present'] = _vibe_report_present
entry['contradictions'] = _contras

with open(LOG, 'a') as f:
    f.write(json.dumps(entry) + '\n')

tok = entry.get('tokens_total', '?')
saved = entry['cost_claude_eq'] - entry.get('cost_usd', 0)
saved_str = f', saved ~${saved:.4f} vs Claude' if saved > 0 else ''
adapt_str = f'  [{",".join(adaptations)}]' if adaptations else ''
reason_str = f'  {_reason}' if _reason != 'ok' else ''
print(f'[log] → {LOG}  ({tok} tokens, exit {_exit}, {duration}s{saved_str}{reason_str}{adapt_str})')

# Ground-truth report: the last block before the RESULT verdict line.
print('')
print('=== DELEGATION REPORT ===')
for _rline in _report:
    print(_rline)

# Loud, last-line verdict. failure_reason used to be a single word at the end of
# the [log] line, with exit code 0 — easy to read past. Callers (and Claude) must
# treat FAILED as "nothing usable landed", whatever stdout narrated.
_FAIL_HINTS = {
    'wrote_nothing':     'Vibe read/explored but never wrote (turn cap hit? large file? see WRITE AUDIT)',
    'silent_exit':       'Vibe never engaged (0 tokens, 0 tool calls)',
    'near_empty':        'Vibe produced almost nothing',
    'narrated_no_tools': 'Vibe described the change instead of calling a write tool',
    'denied':            'a tool call was auto-denied (path outside workdir?)',
    'write_mismatch':    'a write Vibe journaled did NOT land on disk (see WRITE AUDIT)',
    'syntax_error':      'files written but syntax check failed',
    'sr_fail':           'search_replace did not match (anchor/UTF-8?)',
    'exit_error':        'vibe exited non-zero',
    'turn_cap':          'out of turns (auto-continue rounds included) — task PARTIAL; split it, or resume (below)',
    'timeout':           'time budget used up before Vibe finished — task PARTIAL',
    'budget_limit':      'token/price/length limit hit — task PARTIAL',
    'refusal':           'the model refused the task',
    'infra_error':       'the model API failed mid-run, even after one automatic resume',
    'usage_error':       'Vibe or the model API rejected the request itself (bad agent name, flag, model setting) — fix it, do NOT retry verbatim',
}
_sid = stats.get('session_id') or ''
_verr = stats.get('vibe_error') or ''
if _reason in _FAIL_HINTS:
    if _reason in ('turn_cap', 'timeout', 'budget_limit', 'infra_error') and _fc > 0:
        # A limit stop does not mean nothing landed: a write in flight when the
        # limit hit can still be on disk (see the late-write rescan above).
        # Seen 2026-11-10: FAILED [timeout] printed with files_changed=1, and the
        # supervisor concluded "nothing was done" without reading the diff.
        print(f'=== RESULT: PARTIAL [{_reason}] — {_fc} file(s) DID land on disk despite the limit. Read the DIFF / git status below BEFORE relaunching anything. ===')
    else:
        print(f'=== RESULT: FAILED [{_reason}] — {_FAIL_HINTS[_reason]}. Do NOT report success; inspect git diff. ===')
    if _verr:
        print(f'    vibe error: {_verr}')
    if _sid and _reason in ('turn_cap', 'timeout', 'budget_limit', 'infra_error'):
        print(f'    resume this session (keeps its context — for the rest of THIS task, never a fresh session): vibe-delegate <workdir> "continue" <turns> --resume {_sid}')
elif _agent in _readonly_agents:
    print('=== RESULT: READ-ONLY run (no writes expected) ===')
else:
    if _reason == 'ok_resumed_nothing_left':
        print('=== RESULT: OK — resumed session finished with nothing left to write (earlier run did the work); read its final answer ===')
    elif os.environ.get('DELEGATE_HAD_SESSION') == '1':
        print(f'=== RESULT: OK — {_fc} file(s) changed, verified against the session journal ===')
    else:
        print(f'=== RESULT: OK (UNVERIFIED) — {_fc} file(s) changed on disk, but no session journal was found to cross-check. Read git diff. ===')
try:
    with open(os.environ['DELEGATE_REASON_FILE'], 'w') as _rf:
        _rf.write(_reason)
except (KeyError, OSError):
    pass
PYLOG

# Exit 3 = vibe itself exited 0 but produced nothing usable (see RESULT line).
# Keeps `vibe-delegate ... && next-step` chains from sailing past a failed run.
FINAL_REASON=$(cat "$DELEGATE_REASON_FILE" 2>/dev/null)
case "$FINAL_REASON" in
  wrote_nothing|silent_exit|near_empty|narrated_no_tools|denied|write_mismatch|syntax_error|sr_fail|turn_cap|timeout|budget_limit|refusal|infra_error|usage_error)
    if [ "$VIBE_EXIT" -eq 0 ]; then exit 3; fi ;;
esac
exit $VIBE_EXIT
}
