Session refresh

From leopu00/job-hunter-team · View interactive version

Session refresh is an AI agent skill from the GitHub repository leopu00/job-hunter-team. Doctor-only. Context-refresh round: for each agent session read its real context occupancy (provider client-side command, zero tokens) and refresh ONLY sessions whose context window is >50% full — do a retrospective (capture + interview + analytics), append a dense synthesis to the growing daily jou

How to use this skill

Skill file

session-refresh — clear agent context, keep continuity

You (the Dottore) are spawned at a scheduled slot (+30min from the work-window start, or at mid window). Your job this round is not liveness-pinging — it is to refresh the context of the active agent sessions: each long-running session accumulates a bloated context window; you summarize what it did, persist it, then recreate the session fresh and hand back the continuation.

Why this exists: the old Dottore burned ~51% of team budget pinging [HEALTH] every 2h with zero useful checks. This round is rare (2×/window) and produces a durable, dense journal of the team's work.

Step 0 — window start (the analytics window)

WIN_START=$(python3 -c "import sys; sys.path.insert(0,'/app'); from shared.skills.working_hours import current_window_bounds as b; w=b(); print(w[0].isoformat() if w else '')")
# 24/7 (no window): fall back to the last 6h
[ -z "$WIN_START" ] && WIN_START=$(python3 -c "import datetime; print((datetime.datetime.now(datetime.timezone.utc)-datetime.timedelta(hours=6)).isoformat())")
ROUND_ID=$(date -u +%Y%m%dT%H%M%SZ)
DAY=$(date -u +%F)
JOURNAL=/jht_home/logs/doctor-retrospective.jsonl
ROUND_HEADS_UP_SENT=0

Step 1 — list sessions + age, decide order

tmux list-sessions -F '#{session_name}|#{session_created}'

Step 1.4 — TTL: **every agent session lives at most 12 hours**

TTL_H="${JHT_AGENT_MAX_SESSION_AGE_H:-12}"
AGE_H=$(( ( $(date -u +%s) - $(tmux display-message -p -t "$S" '#{session_created}') ) / 3600 ))
[ "$AGE_H" -ge "$TTL_H" ] && echo "TTL EXPIRED ($AGE_H h) → refresh MANDATORY"

If AGE_H ≥ TTL_H the session is refreshed. Full stop. The TTL is checked before

everything else and overrides every skip in this skill — there is no exception, no

override, no "but":

| would normally skip | past the TTL |

|---|---|

| skipped_fresh (age < 40min) | impossible past 12h, but the TTL wins anyway |

| skipped_lowctx (context ≤ 50%) | ignored — a session at 4% after 30h is still refreshed |

| skipped_parked (PARKED, Step 4) | ignored — parked or not, the TTL applies |

| "the agent is working" | ignored — capture its state in the seed and recreate |

| outside the working-hours window | ignored — the TTL is never suspended (see Rules) |

Log action=recreated with reason=ttl and the measured session_age_h. Then go straight

to Steps 2 → 7 (capture, analytics, synthesis, recreate + resume): **skip Step 1.5 and

Step 4 entirely**, they can only produce a skip and a skip is not available here.

Why age alone, with no health heuristic on top: in the 2026-07-28/29 incident the sessions

were 38.5 · 29.5 · 27.0 · 14.5 · 14.2 hours old, every heuristic reported "healthy", and

the team was paralysed for eleven hours. Contexts were under 50%, so nothing touched them.

A TTL has no heuristics to get wrong.

Step 1.5 — CONTEXT CHECK (the *ordinary* refresh trigger: **>50%**)

Only for sessions that did not trip the TTL in Step 1.4.

Refresh ONLY sessions whose context window is more than 50% full. Read the real occupancy with the provider's client-side context command — it costs zero tokens (rendered locally, no LLM call) and is instant. Age is NOT the trigger anymore: an old-but-empty session (e.g. an idle Mentor at 2%) must be SKIPPED, a bloated session must be refreshed.

Two hard requirements — ignore them and you burn budget instead of saving it:

S=<session>
# provider → command:  claude → /context   ·   codex → /status   ·   kimi → (verify on its TUI)
tmux send-keys -t "$S" Escape; sleep 1
tmux send-keys -t "$S" C-u;    sleep 1          # clear the input line (mandatory)
tmux send-keys -t "$S" "/context"; sleep 1
tmux send-keys -t "$S" Enter;  sleep 3
PCT=$(tmux capture-pane -p -t "$S" | grep -aoE '[0-9.]+k?/[0-9.]+[km] tokens \([0-9]+%\)' | tail -1 | grep -aoE '\([0-9]+%\)' | tr -dc '0-9')
tmux send-keys -t "$S" Escape                   # dismiss the panel
echo "context=$PCT%"

Decide from $PCT (parsed from a line like 24.9k/1m tokens (2%)):

Step 1.6 — notify the Capitano once, before the first refresh

Only when this round has selected its first real refresh target (TTL or context),

send one heads-up to the Capitano before Step 2. Do not repeat it for every

agent, and do not send it when the round will only log skips:

if [ "$ROUND_HEADS_UP_SENT" -eq 0 ]; then
  if /app/agents/_skills/tmux-send/jht-tmux-send CAPITANO "[@dottore -> @capitano] [HEADS-UP] Context refresh starting: workers first, coordinators last, you last. Do not start short-lived assignments until the completion report."; then
    ROUND_HEADS_UP_SENT=1
  else
    echo "HEADS-UP delivery failed — aborting the rich refresh before any recreate"
    exit 1
  fi
fi

This is coordination, not a second scheduler or a request for permission. The

round remains sequential and the Capitano stays alive until the end. Delivery

is a precondition: a nonzero sender exit aborts the round before capture/kill;

never mark a failed heads-up as sent.

Step 2 — per session: capture (wide + salient)

Capture the WHOLE scrollback once, then the salient lines — do NOT load thousands of lines into your own context, grep the highlights:

tmux capture-pane -p -S - -t "$S" > /tmp/cap_$S.txt          # full scrollback to file
tail -n 60 /tmp/cap_$S.txt                                    # recent state
grep -nE '\[ERROR\]|Traceback|throttle|EXCLUDED|inserted|\[FEEDBACK\]|\[RETRO\]|spawn|Killed' /tmp/cap_$S.txt | tail -40   # salient moments

Step 3 — analytics (objective numbers, not just the agent's story)

python3 /app/shared/skills/doctor_analytics.py "$S" "$WIN_START"

Returns JSON: produced{found,analyzed,scored,written,reviewed}, communications{sent,received,top_peers}, throttles{events,max_sleep_s}, last_captain_msg, session_age_h, role, instance.

Step 4 — PARKED check (data-driven, do NOT guess)

A session is PARKED (the Capitano deliberately left it on but is not using it — e.g. a Scout left over from the previous window that the Capitano did not assign today) when all hold:

If PARKED → do NOT recreate to restart it. Write the synthesis (Step 6) with action=skipped_parked and move on. (Recreating it would turn a deliberate park into work the Capitano did not want.) If you do recreate it for hygiene, the resume message MUST say it was idle: [RESUME] you were in STANDBY — stay idle until the Capitano assigns you a queue.

Two hard exceptions to PARKED — this rule described the incident exactly and kept the Doctor's hands off precisely when the team needed it most:

  1. Past the TTL (Step 1.4), PARKED does not apply. Parked or not, a 12h+ session gets recreated.
  2. A blocked agent is not a parked agent. "not fresh + produced == 0 + no recent captain message" is also the exact fingerprint of a team whose coordination is broken. The objective signal that separates them: an agent retrying at another agent with no answer is not parked, it is blocked (the retry_loop entries from agent-unblock's scan, and the pane shows the attempts). Same for "every operative idle while quota is available". In those cases do NOT log skipped_parked — clear the block (agent-unblock), then continue this round.

Step 5 — interview the agent

/app/agents/_skills/tmux-send/jht-tmux-send "$S" "[@dottore -> @${s_lower}] [RETRO] Inizio-giornata: 1) intoppi in questa sessione? 2) imparato qualcosa di utile? 3) cosa stavi facendo proprio ora (per il resume)? Rispondi denso, 3-4 righe."
sleep 45
tmux capture-pane -p -S -40 -t "$S" | tail -25   # read the reply

(Skip the interview for PARKED/fresh sessions — there is nothing in-flight to ask about.)

Step 6 — append the DENSE synthesis (append-only, grows daily)

One JSONL entry per agent per round. Combine analytics + interview into a tight summary. NEVER overwrite — multiple Doctors across the day all append.

python3 - "$S" "$ROUND_ID" "$DAY" "$JOURNAL" <<'PY'
import json, sys, datetime
session, round_id, day, journal = sys.argv[1:5]
entry = {
  "ts": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00","Z"),
  "round_id": round_id, "day": day,
  "timing": "start+30",          # or "mid"  — set to the slot you were spawned for
  "session": session, "role": "<role>", "session_age_h": 0.0,
  "analytics": { },              # paste the doctor_analytics.py JSON here
  "interview": {"intoppi": "...", "imparato": "...", "summary_denso": "..."},
  "action": "recreated",         # recreated | skipped_lowctx | skipped_parked | skipped_fresh
  "context_pct": 0,              # measured context occupancy from Step 1.5 (the >50% gate)
  "resume_msg_sent": False,
}
with open(journal, "a") as f:
    f.write(json.dumps(entry, ensure_ascii=False) + "\n")
print("appended", session)
PY

Step 7 — recreate + resume (if the TTL tripped, OR context **>50%** and NOT fresh, NOT parked)

Atomic refresh — you already captured the context in Step 2, so killing is safe:

ROLE=<role>; N=<instance>      # from analytics; recreate the SAME number (no dice — the die is for NEW spawns only)
tmux kill-session -t "$S"
bash /app/.launcher/start-agent.sh "$ROLE" "$N"
sleep 8
# CAPITANO only: the [MODALITA' CORRENTE] section, read FROM DISK right now (never
# from the context you are throwing away). Same section heartbeat-bridge.py injects
# every hour. Workers do not get it — the mode is applied by the Capitano.
MODE=""
if [ "$ROLE" = "capitano" ]; then MODE=" $(python3 /app/shared/skills/mode_banner.py line)"; fi
LANGUAGE=" $(python3 /app/shared/skills/text_language.py line)"   # the team's language by name (RULE-T14): every role, not only the Capitano
/app/agents/_skills/tmux-send/jht-tmux-send "$S" "[@dottore -> @${s_lower}] [RESUME] Contesto pre-refresh: stavi facendo <X>; avevi completato <Y> (analytics: produced=<...>); il prossimo passo era <Z>. Riprendi da li'. Coda: <next-for-role>.$LANGUAGE$MODE"

Set resume_msg_sent=True in the journal entry. Then move to the next session (pace ~15-20s between agents).

Rules

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.