#!/bin/sh
# Session context budget: nudge, then gate.
#
# WHY: a session's per-turn cost grows with its own length — every hook payload and tool result
# already in context is re-read on every subsequent turn. Nothing in the lifecycle measured or
# bounded that, so sessions ran until the model degraded or the developer noticed. This script is
# the missing bound. It makes "one session, one task" the path of least resistance instead of a
# discipline the developer has to remember.
#
# Called three ways, all fed the harness hook JSON on stdin:
#   session-budget.sh gate      -> UserPromptSubmit: silent, advisory, or refuses the prompt
#   session-budget.sh statusline-> StatusLine: one line, never enters context (free nudging)
#   session-budget.sh checkpoint-> Stop: once per session, forces the wrap the gate can only advise
#
# Context is READ, not estimated. Every assistant line in the transcript carries `message.usage`
# from the API, and input_tokens + cache_read + cache_creation is exactly what the model was sent
# that turn. Anchor on the last one and add only the characters written since.
#
# The previous version summed message TEXT over the whole file and was wrong in both directions.
# Measured against transcript 16346915 (2026-08-05), which the gate had trapped:
#   before /compact   char sum 138669   vs  usage 459353 / compactMetadata.preTokens  460032
#   after  /compact   char sum 142988   vs  compactMetadata.postTokens  25725
# 3.3x UNDER before, 5.5x OVER after. Under, because message text excludes the system prompt, tool
# schemas, images, and thinking blocks, and 4 chars/token is wrong for JSON. Over, because /compact
# APPENDS a compact_boundary to the same file and never truncates it — so a whole-file sum is
# monotonically non-decreasing and can never fall back under CEILING once crossed. That made the
# ceiling a permanent trap: every refusal appended more text and pushed the number further up,
# while /compact reported "Not enough messages to compact" on a session that really held ~26k.
#
# Hence the two anchors, most recent wins: an assistant turn's own usage, or compactMetadata's
# postTokens when a compaction has happened but no turn has run since.
#
# Fail-open everywhere: a budget script that blocks work because `python3` is missing is worse than
# the problem it solves.

set -u

MODE="${1:-gate}"

# Characters per token, applied to message text only (not file bytes). ~4 is the usual ratio for
# English prose and code; raise it to nag later, lower it to nag earlier.
BYTES_PER_TOKEN="${COGITO_CTX_BYTES_PER_TOKEN:-4}"
# Thresholds moved 60/90/120 -> 100/150/200 because the MEASUREMENT changed underneath them, not
# because the policy got laxer. The old numbers were calibrated against the char-sum estimator,
# which ran ~3.3x under real usage before a compaction — so "60k" on that scale was already well
# past 100k of real context. Reading usage directly makes the number honest, and the thresholds
# have to move with it or the gate would fire at roughly a third of the intended budget. These
# match the ladder documented in ~/.claude/CLAUDE.md, which is what the developer is told to
# expect. The reasoning for keeping them low still holds: retrieval here is cheap and precise
# (bounded mem_search, work_hierarchy for a handoff id, automatic re-brief after a compaction),
# so losing context costs ~1-2k to rebuild while holding it costs the full size on EVERY
# remaining turn.
NUDGE="${COGITO_CTX_NUDGE:-100000}"
WARN="${COGITO_CTX_WARN:-150000}"
CEILING="${COGITO_CTX_CEILING:-200000}"
# Self-healing boundary: at the ceiling, ask the daemon to type /compact into this very terminal.
# "off" disables; "dry" resolves the target without sending keys (for verification).
AUTOCOMPACT="${COGITO_CTX_AUTOCOMPACT:-on}"
# Parked 2026-08-05: the ceiling refused a live session at 214k, and the policy behind it is
# unproven — the metric that matters is re-entry cost, not session length. Enforcement is flagged
# off until that is measured. Nothing below is removed; every branch still exists and re-arms.
#   on  -> block at CEILING, auto-/compact, advisory injections, Stop self-wrap
#   off -> measure and display only; the statusline still reports honestly
ENFORCE="${COGITO_CTX_ENFORCE:-off}"
# Show this session's bus address in the statusline. On by default: with several agents on one
# machine, "which pane is claude:616e25a1" was previously answerable only by reading scrollback,
# and a message acted on by the wrong session cost three sessions an hour of work on 2026-08-07.
# The statusline is the right home for it rather than the cmux tab title — the tab already carries
# task identity, and it truncates at a width that would cut the address first. "off" disables.
SHOW_ADDRESS="${COGITO_STATUSLINE_ADDRESS:-on}"

payload=$(cat 2>/dev/null) || exit 0
[ -n "$payload" ] || exit 0

# An unrecognized MODE must fail open, not fall into gate. `checkpoint` was added in ca575943, so
# a Stop hook wired to a deployed copy that predates it passes an argument that copy has never
# heard of — and MODE="${1:-gate}" silently turned that into the PROMPT gate running against a
# Stop payload, which the guard above the gate branch then has to catch. Same EPIPE reason as the
# ENFORCE check below for sitting after the drain rather than beside the MODE assignment.
case "$MODE" in
  gate|statusline|checkpoint) ;;
  *) exit 0 ;;
esac

# Parked (see ENFORCE): the statusline still measures and reports, but the two modes that can
# interrupt a session return here — so a parked gate spawns no jq/python and costs nothing per
# turn. Placed AFTER the read so stdin is drained; exiting before it risks EPIPE on the harness.
[ "$ENFORCE" = "on" ] || [ "$MODE" = "statusline" ] || exit 0

# Prefer jq; fall back to sed so a missing jq degrades to "no gate" rather than a broken hook.
if command -v jq >/dev/null 2>&1; then
  transcript=$(printf '%s' "$payload" | jq -r '.transcript_path // empty' 2>/dev/null)
  sid=$(printf '%s' "$payload" | jq -r '.session_id // empty' 2>/dev/null)
else
  transcript=$(printf '%s' "$payload" \
    | sed -n 's/.*"transcript_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)
  sid=$(printf '%s' "$payload" \
    | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)
fi

# harness:sess8 — the same address peers use with agent_msg_send, derived the same way the daemon
# derives it (dashes stripped, first 8 chars), so what the operator reads matches what they can
# type. Empty when the payload carries no session_id; the statusline then degrades to ctx alone.
ADDRESS=""
if [ "$SHOW_ADDRESS" != "off" ] && [ -n "${sid:-}" ]; then
  ADDRESS="${BREATHE_HARNESS:-claude}:$(printf '%s' "$sid" | tr -d '-' | cut -c1-8)"
fi

# A statusline with no readable transcript still knows who it is, and identity is the half the
# operator cannot recover any other way — so print the address alone rather than nothing.
if [ -z "$transcript" ] || [ ! -f "$transcript" ]; then
  [ "$MODE" = "statusline" ] && [ -n "$ADDRESS" ] && printf '%s\n' "$ADDRESS"
  exit 0
fi

if command -v python3 >/dev/null 2>&1; then
  est=$(python3 - "$transcript" "$BYTES_PER_TOKEN" <<'PY' 2>/dev/null
import json, sys
path, per = sys.argv[1], float(sys.argv[2] or 4)
if per <= 0:
    per = 4.0

def blocks(content):
    """Chars the model actually carries: prose, thinking, tool inputs, tool results."""
    if isinstance(content, str):
        return len(content)
    if not isinstance(content, list):
        return 0
    n = 0
    for b in content:
        if not isinstance(b, dict):
            continue
        n += len(b.get('text') or '')
        n += len(b.get('thinking') or '')
        if b.get('type') == 'tool_use':
            n += len(json.dumps(b.get('input') or ''))
        elif b.get('type') == 'tool_result':
            n += blocks(b.get('content'))
    return n

def reported(msg):
    """Exact context the API was sent for this turn, or None if the line predates usage."""
    u = msg.get('usage')
    if not isinstance(u, dict):
        return None
    n = 0
    for key in ('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'):
        v = u.get(key)
        if isinstance(v, (int, float)):
            n += int(v)
    return n or None

base = None   # exact token count at the most recent anchor
tail = 0      # chars written since that anchor — the only part still estimated
whole = 0     # chars over the whole file, used only when no anchor exists at all
try:
    with open(path, errors='replace') as fh:
        for line in fh:
            try:
                d = json.loads(line)
            except Exception:
                continue
            kind = d.get('type')
            if kind == 'system' and d.get('subtype') == 'compact_boundary':
                # A compaction reset the window. postTokens is exactly what survived it.
                meta = d.get('compactMetadata')
                post = meta.get('postTokens') if isinstance(meta, dict) else None
                if isinstance(post, (int, float)) and post >= 0:
                    base, tail = int(post), 0
                continue
            # Only real turns. Everything else in a transcript is host bookkeeping.
            if kind not in ('user', 'assistant'):
                continue
            # The post-compact summary is already inside postTokens; counting it double-bills.
            if d.get('isCompactSummary'):
                continue
            m = d.get('message')
            if not isinstance(m, dict):
                continue
            n = blocks(m.get('content'))
            whole += n
            tail += n
            # A subagent's usage describes ITS window, not this session's.
            if kind == 'assistant' and not d.get('isSidechain'):
                real = reported(m)
                if real:
                    # This turn's own output is what becomes input on the next one.
                    base, tail = real, n
except Exception:
    raise SystemExit(1)
print(int(base + tail / per) if base is not None else int(whole / per))
PY
  )
fi
# Fallback when python3 is absent: raw size scaled by the measured ~5.5x envelope ratio, so a
# degraded estimate still lands in the right order of magnitude instead of blocking early.
if [ -z "${est:-}" ]; then
  bytes=$(wc -c <"$transcript" 2>/dev/null | tr -d ' ') || exit 0
  [ -n "$bytes" ] || exit 0
  est=$(awk -v b="$bytes" 'BEGIN { printf "%d", b / 22 }')
fi
[ -n "$est" ] || exit 0
k=$((est / 1000))

if [ "$MODE" = "statusline" ]; then
  # The statusline is the one channel that costs zero context, so the routine nudging lives here
  # and only the two thresholds that need to interrupt emit in-context text.
  pct=$((est * 100 / CEILING))
  if   [ "$est" -ge "$CEILING" ]; then mark="CEILING — /wrap then /clear"
  elif [ "$est" -ge "$WARN" ];    then mark="wrap now"
  elif [ "$est" -ge "$NUDGE" ];   then mark="finish this task"
  else mark=""
  fi
  # Address first: it is fixed-width and never the part worth losing if the line gets clipped.
  prefix=""
  [ -n "$ADDRESS" ] && prefix="$ADDRESS · "
  # Report occupancy to the control plane. This script already knows the exact number and renders
  # it several times a minute; agent_fleet reported tokens:null for want of it, which is what
  # forced a conductor to screen-scrape a pane and therefore ruled out headless or remote
  # conducting entirely. The value is the same `est` printed below, so the statusline and the
  # control plane can never disagree about the same session.
  #
  # THROTTLED, because the statusline renders far more often than steering needs. BACKGROUNDED and
  # fail-open, because a statusline that stalls on a slow daemon is worse than one missing a field.
  if [ -n "$sid" ] && [ "${COGITO_CTX_REPORT:-on}" != "off" ]; then
    sess8=$(printf '%s' "$sid" | tr -d '-' | cut -c1-8)
    stamp="${TMPDIR:-/tmp}/cogito-ctx-report-$sess8"
    now=$(date +%s 2>/dev/null || echo 0)
    last=0
    [ -f "$stamp" ] && last=$(cat "$stamp" 2>/dev/null || echo 0)
    case "$last" in ''|*[!0-9]*) last=0 ;; esac
    if [ "$now" -gt 0 ] && [ $((now - last)) -ge "${COGITO_CTX_REPORT_INTERVAL:-20}" ]; then
      printf '%s' "$now" >"$stamp" 2>/dev/null || true
      # profile=full for the same reason the autocompact call above uses it: the agent profile is
      # enforced at CALL time, so an agent-profile request would fail the moment it is tightened.
      printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"agent_activity_record","arguments":{"record_type":"telemetry","session":"%s","context_tokens":%d,"context_ceiling":%d}}}' \
        "$sess8" "$est" "$CEILING" \
        | curl -sf --connect-timeout 0.3 --max-time 2 -X POST \
            "${BREATHE_MCP_ENDPOINT:-http://127.0.0.1:24567}/mcp?profile=full" \
            -H 'content-type: application/json' --data-binary @- >/dev/null 2>&1 &
    fi
  fi
  if [ -n "$mark" ]; then
    printf '%sctx %dk/%dk (%d%%) · %s\n' "$prefix" "$k" "$((CEILING / 1000))" "$pct" "$mark"
  else
    printf '%sctx %dk/%dk (%d%%)\n' "$prefix" "$k" "$((CEILING / 1000))" "$pct"
  fi
  exit 0
fi

# --- checkpoint mode (Stop) ---
# The gate below can only speak when a HUMAN types, and the only remedy it can name is /wrap — a
# skill a human has to type. So a session that crosses the threshold mid-task stalls: the model
# correctly says "I'm past the wrap threshold, I'd stop here" and then waits to be told to do its
# own bookkeeping. This mode closes that loop at turn end, where the model still holds the context
# needed to write a real summary and no human is in the way.
#
# It fires ONCE per session. A Stop hook that blocks repeatedly is an infinite loop, so there are
# two independent guards: the harness's own stop_hook_active flag, and a sentinel written BEFORE
# the block is emitted so even a crash between the two cannot re-arm it.
if [ "$MODE" = "checkpoint" ]; then
  [ "$est" -ge "$NUDGE" ] || exit 0
  command -v jq >/dev/null 2>&1 || exit 0

  # Set by the harness when this Stop already blocked once. Continuing past it re-enters the hook.
  active=$(printf '%s' "$payload" | jq -r '.stop_hook_active // false' 2>/dev/null)
  [ "$active" = "true" ] && exit 0

  sid=$(printf '%s' "$payload" | jq -r '.session_id // empty' 2>/dev/null)
  [ -n "$sid" ] || exit 0
  sentinel="${TMPDIR:-/tmp}/cogito-selfwrap-${sid}"
  [ -e "$sentinel" ] && exit 0
  : >"$sentinel" 2>/dev/null || exit 0

  # One forced turn, not open-ended work. The instruction is deliberately terminal: record the
  # continuation and stop. That is the opposite of extending the session — it is what lets the
  # session END cleanly instead of dying at the ceiling with nothing written.
  reason="[self-wrap ~${k}k of $((CEILING / 1000))k] Before you stop: call session_checkpoint with a real summary of what changed and what is next, then write the continuation. Do not start new work, do not re-run verification, do not summarize for the user beyond one line. This fires once — after it, stopping is expected."
  jq -n --arg r "$reason" '{decision: "block", reason: $r}'
  exit 0
fi

# --- gate mode (UserPromptSubmit) ---

# Structural assertion that this really is a prompt event. The ceiling branch below answers with
# decision:"block"; delivered on Stop that FORCES ANOTHER TURN — the exact inversion its own
# comment warns against — and it cannot be broken from inside the session, because the /wrap
# exemption reads .prompt and a Stop payload has no such key, so it never matches. Observed
# 2026-08-05 in session 9ac29979: the ceiling message replayed as Stop feedback at 211k then 226k
# with no reachable remedy. The mode guard after the drain closes the known route in (a Stop hook
# on a copy predating checkpoint mode); this closes the class, by making the invariant structural
# instead of a comment. A UserPromptSubmit payload always carries "prompt", possibly empty; Stop
# carries stop_hook_active/session_id instead. Fail open when the key cannot be confirmed.
if command -v jq >/dev/null 2>&1; then
  printf '%s' "$payload" | jq -e 'has("prompt")' >/dev/null 2>&1 || exit 0
else
  printf '%s' "$payload" | grep -q '"prompt"[[:space:]]*:' || exit 0
fi

emit_context() {
  # additionalContext is the documented way to add text to a turn. Kept to a single line: this
  # fires on every prompt past the threshold, so a paragraph here would itself become the leak.
  if command -v jq >/dev/null 2>&1; then
    jq -n --arg t "$1" \
      '{hookSpecificOutput: {hookEventName: "UserPromptSubmit", additionalContext: $t}}'
  else
    printf '%s\n' "$1"
  fi
  exit 0
}

# The commands that END a session must never be refused by the gate that tells you to run them.
# /wrap and /save are skills, so they arrive as ordinary prompts and the block would swallow them —
# leaving the advice "run /wrap then /clear" impossible to follow from inside the blocked session.
# Matched on the leading token only, so a prompt that merely mentions /wrap in prose still blocks.
if command -v jq >/dev/null 2>&1; then
  prompt=$(printf '%s' "$payload" | jq -r '(.prompt // "") | sub("^[[:space:]]+"; "")' 2>/dev/null)
  case "$prompt" in
    /wrap|/wrap\ *|/save|/save\ *|/back|/back\ *|/clear|/clear\ *|/compact|/compact\ *) exit 0 ;;
  esac
fi

if [ "$est" -ge "$CEILING" ]; then
  # Self-heal: ask the daemon to type /compact into this terminal. This is the ONE safe moment to
  # do it — the prompt below is refused, so nothing is in flight and no tool call is mid-execution.
  # Fired before emitting the block so the keystroke is queued while the turn is already stopping.
  # Once per session: a marker keyed on the transcript, so a session past the ceiling does not
  # compact on every subsequent prompt.
  #
  # This DEPENDS on the exemption list above. The /compact typed here arrives as an ordinary
  # prompt, so without that allowlist the gate would refuse its own remedy and the session would
  # stay stuck at the ceiling — the two halves are not independent features.
  if [ "$AUTOCOMPACT" != "off" ] && command -v python3 >/dev/null 2>&1; then
    marker="${TMPDIR:-/tmp}/cogito-autocompact-$(printf '%s' "$transcript" | shasum | cut -c1-16)"
    if [ ! -f "$marker" ]; then
      : >"$marker" 2>/dev/null
      sid=$(printf '%s' "$payload" | python3 -c 'import json,sys;print(json.load(sys.stdin).get("session_id",""))' 2>/dev/null)
      if [ -n "$sid" ]; then
        dry=false; [ "$AUTOCOMPACT" = "dry" ] && dry=true
        # profile=full, NOT agent. agent_terminal_wake is deliberately kept off the stable agent
        # surface ("poking an existing terminal is a specialist operation"), and http-dispatcher
        # enforces that set at CALL time, not just in tools/list — so an agent-profile call here
        # would come back tool_not_available the moment the default profile is tightened.
        # Short timeouts and -sf: if the daemon is down or slow this degrades to the plain block
        # below rather than hanging every prompt.
        printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"agent_terminal_wake","arguments":{"target":"claude:%s","command":"/compact","mode":"prompt_and_enter","dry_run":%s}}}' \
          "$(printf '%s' "$sid" | cut -c1-8)" "$dry" \
          | curl -sf --connect-timeout 0.3 --max-time 3 -X POST \
              "${BREATHE_MCP_ENDPOINT:-http://127.0.0.1:24567}/mcp?profile=full" \
              -H 'content-type: application/json' --data-binary @- >/dev/null 2>&1 || true
      fi
    fi
  fi
  # Blocking the PROMPT is the correct gate. Blocking on Stop would force the model to keep
  # working, which is backwards — the goal is to end the session, not extend it.
  reason="Context ceiling reached (~${k}k). This session is done taking new work.
A /compact has been sent to this terminal; the next turn re-orients from Breathe automatically.
If it did not fire, run /wrap to record the checkpoint and continuation, then /clear.
Resume the thread in a fresh session with /back — it costs a fraction of continuing here.
Those commands are exempt from this gate and will go through."
  if command -v jq >/dev/null 2>&1; then
    jq -n --arg r "$reason" '{decision: "block", reason: $r}'
  else
    printf '%s\n' "$reason"
  fi
  exit 0
fi

if [ "$est" -ge "$WARN" ]; then
  emit_context "[context ~${k}k of $((CEILING / 1000))k] Wrap now: call session_checkpoint with a real summary of what changed and what is next, then /wrap and /clear. Past $((CEILING / 1000))k new prompts are refused."
fi

if [ "$est" -ge "$NUDGE" ]; then
  emit_context "[context ~${k}k] Finish the current task, then /wrap and /clear. Do not start a new task in this session."
fi

exit 0
