#!/usr/bin/env bash # stop_session.sh — multi-agent-mux-stop 의 부속 스크립트 # Usage: # bash stop_session.sh --session [--agent claude|agy|hermes|grok|opencode|codex] [--herdr-session ] \ # [--reason ] [--purge-conversation] [--yes] # # 동작: 항상 graceful stop 입니다. send-keys 로 정상 종료를 유도하고 # (미종료 시 SIGTERM → SIGKILL 폴백), kill 직전에 이 세션(pane)의 검증된 # conversation id 만 row 에 확정 기록해 다음 resume 이 tier-1(race-free) # 으로 복원되게 합니다. status 는 running -> stopped 로 전이합니다. # 멱등: 이미 stopped 면 no-op + exit 0. # # 옵션: # --session — 대상 세션 (필수) # --agent — claude | agy | hermes | grok | opencode | codex # (권장: 항상 명시. 미지정 시 레지스트리 기록으로 # 해석 — agent 필드 → 세션명 접미사 → pane.cmd; # 셋 다 실패하면 exit 2) # --herdr-session — isolated herdr session name (alias: --herdr-server) # --reason — 상태 전이 사유 (stop_reason). 기본값 manual_stop # --purge-conversation — 디스크의 conversation artifact 와 세션 부속 경로까지 # 삭제하고 레지스트리 행(YAML+DB)을 지우며 # resume 불가. --yes 없이는 확인 프롬프트(exit 3) # --yes — --purge-conversation 의 확인 프롬프트 생략 # # 폐지된 옵션: --mode / --capture-id / --graceful 는 각각 exit 2 로 거부됩니다. # graceful 종료와 id 캡처는 이제 무조건 수행되며, soft/hard 모드 # 구분은 --purge-conversation 유무로 대체되었습니다. # # Exit codes: # 0 = success (or already-stopped no-op; or a session with no row closed) # 1 = YAML not found / its row unreadable / not registered and not on the herdr server # 2 = invalid args | 3 = interactive confirmation required (--yes 누락) # 4 = purge aborted (herdr session or an agent process holding the conversation survived the kill chain) # 5 = no row, and herdr runs the session outside this workspace (refused, nothing changed) # 6 = no row, and its herdr session survived kill-session (registry unchanged) set -euo pipefail # shellcheck disable=SC1091 _script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" _lib_sh="$(cd "$_script_dir/../.." && pwd)/lib.sh" [ -f "$_lib_sh" ] || _lib_sh="${WORKSPACE_ROOT:-$PWD}/.agents/skills/lib.sh" source "$_lib_sh" usage() { cat < [--agent claude|agy|hermes|grok] [--herdr-session ] [--reason ] [--purge-conversation] [--yes] Arguments: --session — target session name (required) --agent — claude | agy | hermes | grok (recommended: always pass it) (falls back to the registry record: agent field -> session-name suffix -> pane.cmd) --herdr-session — specify isolated herdr session name (alias: --herdr-server) --herdr-workspace — recorded label only; never selects a socket (use --herdr-session for that). Note: stop has no --workspace flag — the session's own workspace is read from its registry row, not from where you stand. --reason — stop_reason field (default: manual_stop) --purge-conversation — also delete on-disk conversation artifacts; the registry row is removed and resume is impossible --yes — skip the --purge-conversation confirmation prompt EOF } SESSION_NAME="" AGENT="" HERDR_SERVER_OPT="" HERDR_WORKSPACE_OPT="" PURGE=0 YES=0 GRACEFUL=1 REASON="manual_stop" STOP_MODE=1 while [ $# -gt 0 ]; do case "$1" in --session) SESSION_NAME="$2"; shift 2 ;; --agent) AGENT="$2"; shift 2 ;; --herdr-session|--herdr-server) HERDR_SERVER_OPT="$2"; shift 2 ;; --herdr-workspace) HERDR_WORKSPACE_OPT="$2"; shift 2 ;; --purge-conversation) PURGE=1; shift ;; --yes) YES=1; shift ;; --reason) REASON="$2"; shift 2 ;; --mode|--capture-id|--graceful) echo "ERROR: $1 option is deprecated. Stop now always stops gracefully and captures IDs." >&2 exit 2 ;; -h|--help) usage; exit 0 ;; *) echo "ERROR: unknown arg: $1" >&2; usage; exit 2 ;; esac done if [ -n "$AGENT" ]; then case "$AGENT" in claude|agy|hermes|grok|opencode|codex) ;; *) echo "ERROR: invalid agent type '$AGENT'. Allowed types are: claude, agy, hermes, grok, opencode, codex." >&2; exit 2 ;; esac fi [ -n "$SESSION_NAME" ] || { echo "ERROR: --session required" >&2; usage; exit 2; } [ -f "$AGENT_SESSIONS_YAML" ] || { echo "ERROR: $AGENT_SESSIONS_YAML not found" >&2; exit 1; } # Implement the purging- file lock mechanism if [ "$PURGE" = "1" ]; then touch "$WORKSPACE_ROOT/.mam/purging-$SESSION_NAME" trap 'rm -f "$WORKSPACE_ROOT/.mam/purging-$SESSION_NAME"' EXIT fi AMBIENT_HERDR_SESSION="${HERDR_SESSION_NAME:-}" if [ -n "$HERDR_SERVER_OPT" ]; then export HERDR_SESSION_NAME="$HERDR_SERVER_OPT" else HERDR_SESSION_NAME="$(resolve_herdr_session "$SESSION_NAME" "${WORKSPACE:-$WORKSPACE_ROOT}")" export HERDR_SESSION_NAME fi # Issue #71: a session with no registry row (its create/resume died before # registering it) is closed here - herdr only, the registry is left alone. It # has no agent kind, so --agent is not needed. Only a session herdr runs # inside this workspace is closed; anything else changes nothing. With no row # the server is chosen as create_session.sh chose it: --herdr-session, else # the environment's HERDR_SESSION_NAME, else the workspace's server. stop_rowless() { if [ "$PURGE" = "1" ]; then echo "ERROR: session '$SESSION_NAME' not in $AGENT_SESSIONS_YAML; --purge-conversation needs its row. Nothing changed." >&2 exit 1 fi if [ -z "$HERDR_SERVER_OPT" ] && [ -n "$AMBIENT_HERDR_SESSION" ] && [ "$AMBIENT_HERDR_SESSION" != "default" ]; then export HERDR_SESSION_NAME="$AMBIENT_HERDR_SESSION" fi local info cwd info=$(herdr agent get "$SESSION_NAME" 2>/dev/null) || info="" if [ -z "$info" ]; then echo "ERROR: session '$SESSION_NAME' not in $AGENT_SESSIONS_YAML, and herdr server '${HERDR_SESSION_NAME:-default}' has no agent of that name. Nothing changed." >&2 exit 1 fi cwd=$(printf '%s' "$info" | python3 -c ' import sys, json raw = sys.stdin.read() try: print(json.loads(raw[raw.index("{"):]).get("result", {}).get("agent", {}).get("cwd", "") or "") except Exception: print("") ') if ! PANE_CWD="$cwd" python3 -c ' import os, sys cwd, root = os.environ.get("PANE_CWD", ""), os.environ.get("WORKSPACE_ROOT", "") if not cwd or not root: sys.exit(1) cwd, root = os.path.realpath(cwd), os.path.realpath(root) sys.exit(0 if cwd == root or cwd.startswith(root + os.sep) else 1) '; then echo "ERROR: refusing to stop '$SESSION_NAME': it is not in $AGENT_SESSIONS_YAML, and herdr runs it in '${cwd:-}', outside this workspace ($WORKSPACE_ROOT). Nothing changed." >&2 exit 5 fi echo "session '$SESSION_NAME' has no registry row: closing its herdr session only (registry unchanged)" herdr kill-session -t "$SESSION_NAME" 2>/dev/null || true _wait_session_gone "$SESSION_NAME" 8 || true if herdr has-session -t "$SESSION_NAME" 2>/dev/null; then echo "ERROR: herdr session '$SESSION_NAME' is still running after kill-session (registry unchanged)" >&2 exit 6 fi echo "closed herdr session '$SESSION_NAME' on server '${HERDR_SESSION_NAME:-default}' (no registry row)" exit 0 } # 세션이 YAML 에 있는지 + 해당 row 의 워크스페이스 cwd 및 delegate_job_id 추출. # JSON 으로 emit — cwd 에 '|' 가 들어가도 안전 (review item 7; 기존 cwd|jid 파서 대체). # A registry that cannot be read is not "no row" (Issue #71): stop before herdr. STATE_JSON=$(load_state_json strict) || { echo "ERROR: cannot read $AGENT_SESSIONS_YAML, so whether '$SESSION_NAME' has a row is unknown. Nothing changed." >&2 exit 1 } MAPPED_DATA=$(MAM_STATE_JSON="$STATE_JSON" SESSION_NAME="$SESSION_NAME" python3 -c " import sys, os, json name = os.environ['SESSION_NAME'] d = json.loads(os.environ.get('MAM_STATE_JSON', '{}')) for s in d.get('herdr_sessions', []): if s.get('name') == name: cwd = (s.get('pane') or {}).get('cwd', '') jid = s.get('delegate_job_id', '') or '' cp = s.get('control_plane') or {} print(json.dumps({'cwd': cwd, 'job_id': jid, 'mam_jobs_dir': cp.get('mam_jobs_dir', '') or '', 'delegate_job_logs_dir': cp.get('delegate_job_logs_dir', '') or ''})) sys.exit(0) sys.exit(7) ") || MAPPED_RC=$? # 7 = no row; any other failure (registry unreadable) stops as before. [ "${MAPPED_RC:-0}" -ne 7 ] || stop_rowless if [ "${MAPPED_RC:-0}" -ne 0 ]; then echo "ERROR: cannot read the row of '$SESSION_NAME' from $AGENT_SESSIONS_YAML" >&2 exit 1 fi # --agent 미지정 시 레지스트리 기록으로 해석 (B-21). # ① row['agent'] → ② 세션명 접미사 → ③ pane.cmd 순. 셋 다 실패하면 # 종전과 동일하게 exit 2 (헤더 :27-30 의 종료 코드 계약 유지). if [ -z "$AGENT" ]; then AGENT="$(resolve_agent_type_from_registry "$SESSION_NAME")" || AGENT="" [ -n "$AGENT" ] || { echo "ERROR: cannot infer agent from '$SESSION_NAME'; pass --agent" >&2 exit 2 } fi TARGET_CWD=$(printf '%s' "$MAPPED_DATA" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("cwd",""))') DELEGATE_JOB_ID=$(printf '%s' "$MAPPED_DATA" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("job_id",""))') # Issue #21: a row created against another control plane names its registry. # Order: MAM_JOBS_DIR > the row's control_plane.mam_jobs_dir > WORKSPACE_ROOT > # .mam/jobs; exported so delegate_publish_event (lib.sh) uses the same one. ROW_JOBS_DIR=$(printf '%s' "$MAPPED_DATA" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("mam_jobs_dir",""))') if [ -z "${MAM_JOBS_DIR:-}" ] && [ -n "$ROW_JOBS_DIR" ]; then export MAM_JOBS_DIR="$ROW_JOBS_DIR" fi # Same for the audit log (R3): the cancellation history belongs next to the # registry the row names, not under $WORKSPACE_ROOT/.mam/delegate_job_logs. ROW_LOGS_DIR=$(printf '%s' "$MAPPED_DATA" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("delegate_job_logs_dir",""))') if [ -z "${DELEGATE_JOB_LOGS_DIR:-}" ] && [ -n "$ROW_LOGS_DIR" ]; then export DELEGATE_JOB_LOGS_DIR="$ROW_LOGS_DIR" fi DELEGATE_JOB_TOKEN="" DELEGATE_JOB_ATTEMPT="" if [ -n "$DELEGATE_JOB_ID" ]; then local_info=$(python3 -c " import sys, json, os jid = '$DELEGATE_JOB_ID' reg_dir = os.environ.get('MAM_JOBS_DIR') or (os.path.join(os.environ['WORKSPACE_ROOT'], '.mam', 'jobs') if os.environ.get('WORKSPACE_ROOT') else '.mam/jobs') p = os.path.join(reg_dir, f'{jid}.json') if os.path.exists(p): try: with open(p) as f: d = json.load(f) tok = d.get('dispatch_token', '') att = d.get('attempt_id', d.get('iteration', 1)) print(f'{tok} {att}') except Exception: pass " 2>/dev/null || true) if [ -n "$local_info" ]; then DELEGATE_JOB_TOKEN=$(echo "$local_info" | awk '{print $1}') DELEGATE_JOB_ATTEMPT=$(echo "$local_info" | awk '{print $2}') fi fi # 멱등성: STOP 모드에서 이미 stopped 인 세션이고 purge 가 아닐 때만 no-op + exit 0 if [ "$STOP_MODE" = "1" ] && [ "$PURGE" != "1" ]; then if STOPPED_INFO=$(is_already_stopped "$SESSION_NAME"); then echo "already stopped (status=stopped, $STOPPED_INFO) — no-op" exit 0 fi fi # purge 확인 if [ "$PURGE" = "1" ] && [ "$YES" != "1" ]; then echo "DANGER: --purge-conversation will DELETE this workspace's on-disk conversation." echo " workspace: ${TARGET_CWD:-}" echo " This means: no future multi-agent-mux-resume for this session." echo " Re-run with --yes to confirm." exit 3 fi NOW_ISO=$(date -u +'%Y-%m-%dT%H:%M:%SZ') NOW_EPOCH=$(date +%s) # herdr 상태 + 마지막 TUI 스냅샷 (살아있을 때만; capture-pane 내용은 env 로만 전달) HERDR_ALIVE=0 LAST_STATUS="" if herdr has-session -t "$SESSION_NAME" 2>/dev/null; then HERDR_ALIVE=1 LAST_STATUS=$(herdr capture-pane -t "$SESSION_NAME" -p -S -10 2>/dev/null | tr '\n' ' ' | head -c 500 || true) fi # Issue #63: before the kill, decide the id this stop records and a purge # deletes (lib_py.agents.session_ids): the row's own id; else, for an agent # that writes its id after its first turn, only what the #40 capture proves is # this pane's (nothing once herdr is dead - the reason goes on the row); claude # and grok keep find_workspace_uuid. An id another row records is never used. CAPTURED_UUID="" CAPTURE_STATUS="" PURGE_UUID="" STOP_ID_NOTE="" if [ -n "$TARGET_CWD" ]; then PANE_PID_NOW="" [ "$HERDR_ALIVE" = "1" ] && PANE_PID_NOW=$(herdr list-panes -t "$SESSION_NAME" -F '#{pane_pid}' 2>/dev/null | head -1 || true) eval "$(mam_session_ids stop --session "$SESSION_NAME" --agent "$AGENT" --cwd "$TARGET_CWD" \ --herdr-alive "$HERDR_ALIVE" --pane-pid "$PANE_PID_NOW" --purge "$PURGE")" || true if [ -n "$CAPTURED_UUID" ]; then echo "captured conversation id: $CAPTURED_UUID" else echo "WARN: no conversation id recorded before stop${STOP_ID_NOTE:+ - $STOP_ID_NOTE}"; fi fi delegate_publish_event "$DELEGATE_JOB_ID" progress "terminating" "$DELEGATE_JOB_TOKEN" "$DELEGATE_JOB_ATTEMPT" # graceful 종료: send-keys 로 정상 종료 유도 → 폴백 체인 (SIGTERM → SIGKILL). graceful_stop() { local pane_pid exitkey pane_pid=$(herdr list-panes -t "$SESSION_NAME" -F '#{pane_pid}' 2>/dev/null | head -1 || true) exitkey="$("$(_delegate_py_bin)" -m lib_py.agents exit-key "$AGENT" 2>/dev/null || echo "/exit")" echo "graceful: send-keys '$exitkey' to $SESSION_NAME" if [ "$exitkey" = "Ctrl+C" ] || [ "$exitkey" = "C-c" ]; then herdr send-keys -t "$SESSION_NAME" C-c 2>/dev/null || true else send_keys_safe "$SESSION_NAME" "$exitkey" "stop$$" || echo "graceful: delivery of '$exitkey' unconfirmed (rc=$?) — waiting for the session to exit" fi _wait_session_gone "$SESSION_NAME" 5 || true if ! herdr has-session -t "$SESSION_NAME" 2>/dev/null; then echo "graceful: exited cleanly" return 0 fi echo "graceful: still alive → kill-session (SIGTERM)" herdr kill-session -t "$SESSION_NAME" 2>/dev/null || true _wait_session_gone "$SESSION_NAME" 8 || true if ! herdr has-session -t "$SESSION_NAME" 2>/dev/null; then echo "graceful: terminated after kill-session" return 0 fi echo "graceful: STILL alive → SIGKILL fallback (pane pid $pane_pid)" [ -n "$pane_pid" ] && kill -9 "$pane_pid" 2>/dev/null || true } # herdr 종료: graceful 이면 폴백 체인, 아니면 기존 hard kill. if [ "$GRACEFUL" = "1" ] && [ "$HERDR_ALIVE" = "1" ]; then graceful_stop elif [ "$HERDR_ALIVE" = "1" ]; then herdr kill-session -t "$SESSION_NAME" echo "killed herdr: $SESSION_NAME" else echo "herdr already dead, just updating YAML" fi # Purge pre-gate: 레코드 제거는 herdr 사망이 확인된 경우에만 허용한다. # (kill 체인은 best-effort — 세션이 살아남으면 monitor drift-B 가 # 레코드 없는 세션을 running 으로 자동 재등록해 purge 가 조용히 뒤집힌다) if [ "$PURGE" = "1" ] && [ "$HERDR_ALIVE" = "1" ]; then _wait_session_gone "$SESSION_NAME" 5 || true # SIGKILL 폴백의 비동기 회수 윈도우 흡수 if herdr has-session -t "$SESSION_NAME" 2>/dev/null; then echo "ERROR: session '$SESSION_NAME' is still alive after the kill chain." >&2 echo " Refusing registry removal — records preserved (no state was modified)." >&2 echo " Diagnose the stuck TUI (herdr session attach '$SESSION_NAME'), then re-run" >&2 echo " stop_session.sh --purge-conversation --yes (retry is safe/idempotent)." >&2 delegate_publish_event "$DELEGATE_JOB_ID" cancelled "purge aborted: session still alive; no state was modified" "$DELEGATE_JOB_TOKEN" "$DELEGATE_JOB_ATTEMPT" exit 4 fi fi # Purge process gate (Issue #31): a closed herdr session is not an exited # agent - the process may still be shutting down, or may have outlived a dead # herdr ("herdr already dead" above runs no gate at all). The purge asks the # adapter's own in-use verdict, the one the purge CLI uses, outside the # registry lock. Any answer but "free" (0) keeps everything. if [ "$PURGE" = "1" ] && [ -n "$PURGE_UUID" ]; then inuse_rc=0 inuse_hints="$("$(_delegate_py_bin)" -m lib_py.agents in-use "$AGENT" "$PURGE_UUID" "$TARGET_CWD" --wait 5 2>&1 >/dev/null)" || inuse_rc=$? if [ "$inuse_rc" != "0" ]; then echo "ERROR: conversation $PURGE_UUID is still held by a live agent process (rc=$inuse_rc)." >&2 echo " Refusing purge — records preserved: the registry row and the conversation files are untouched (the session itself may already be down)." >&2 [ -n "$inuse_hints" ] && printf '%s\n' "$inuse_hints" >&2 delegate_publish_event "$DELEGATE_JOB_ID" cancelled "purge aborted: conversation still in use; records preserved" "$DELEGATE_JOB_TOKEN" "$DELEGATE_JOB_ATTEMPT" exit 4 fi fi # INVARIANT: Terminal events for a job must be published AFTER atomic_dump_yaml updates the session status atomic_dump_yaml "$AGENT_SESSIONS_YAML" \ SESSION_NAME="$SESSION_NAME" AGENT="$AGENT" PURGE="$PURGE" \ NOW_ISO="$NOW_ISO" NOW_EPOCH="$NOW_EPOCH" LAST_STATUS="$LAST_STATUS" \ PURGE_UUID="$PURGE_UUID" TARGET_CWD="$TARGET_CWD" \ REASON="$REASON" CAPTURED_UUID="$CAPTURED_UUID" CAPTURE_STATUS="$CAPTURE_STATUS" STOP_ID_NOTE="$STOP_ID_NOTE" <<'PYEOF' import shutil name = os.environ['SESSION_NAME'] agent = os.environ['AGENT'] purge = os.environ['PURGE'] == '1' now = os.environ['NOW_ISO'] home = os.environ['HOME_DIR'] last_status = os.environ.get('LAST_STATUS', '') purge_uuid = os.environ.get('PURGE_UUID', '').strip() ws = os.environ.get('TARGET_CWD', '') reason = os.environ.get('REASON', '') or 'manual_stop' captured = os.environ.get('CAPTURED_UUID', '').strip() target = None for s in d.get('herdr_sessions', []): if s.get('name') == name: target = s break if target is None: print(f"ERROR: disappeared during script: {name}", flush=True) raise SystemExit(1) from lib_py.agents.autopin import claimed_elsewhere, pin_row capture_status = os.environ.get('CAPTURE_STATUS', '').strip() note = os.environ.get('STOP_ID_NOTE', '').strip() claimed = set(claimed_elsewhere(target, d)) if captured and captured in claimed: print(f"WARN: refusing to record {captured} on {name}; another row already claims it", flush=True) if not note: note = f"{captured} is already claimed by another row" captured = '' if purge_uuid and purge_uuid in claimed: print(f"WARN: refusing to purge {purge_uuid} for {name}; another row claims it", flush=True) purge_uuid = '' if not purge: target['status'] = 'stopped' target['stopped_at'] = now target['stopped_at_epoch'] = int(os.environ['NOW_EPOCH']) target['stop_reason'] = reason target['termination_mode'] = 'graceful' if last_status: target['last_visible_status_at_termination'] = last_status # 항상 captured UUID 기록 (purge 가 아닐 때만) if captured and not purge: if agent == 'claude': target['claude_session_id_own'] = captured elif agent == 'agy': target['agy_conversation_id_own'] = captured elif agent == 'hermes': target['hermes_conversation_id_own'] = captured elif agent == 'grok': target['grok_session_id_own'] = captured elif agent == 'opencode': target['opencode_session_id_own'] = captured elif agent == 'codex': target['codex_session_id_own'] = captured if capture_status == 'captured': pin_row(target, agent, captured) target['resumable'] = True elif not purge and note: target['last_visible_status'] = f"stop: {note}" if purge and purge_uuid: from lib_py.agents.registry import get_adapter from lib_py.agents.base import DiscoveryContext adapter = get_adapter(agent) if adapter: ctx = DiscoveryContext(workspace=ws, agent_name=agent, home_dir=home) for item in adapter.purge_artifacts(purge_uuid, ctx): print(f"purged: {item}", flush=True) # Issue #31: report what still carries the uuid, as orc_onboard does. residual = adapter.residual_artifacts(purge_uuid, ctx) for item in residual: print(f"WARN residual: {item}", flush=True) if not residual: print(f"residual: none (agent: {agent})", flush=True) target[adapter.own_key] = None elif purge and not purge_uuid: print("WARN: --purge-conversation requested but no workspace-scoped UUID resolved; nothing purged", flush=True) if purge: d['herdr_sessions'] = [s for s in d.get('herdr_sessions', []) if s.get('name') != name] if purge_uuid: print(f"removed: {name} (registry entry fully purged from YAML+DB)", flush=True) else: print(f"removed: {name} (registry entry purged from YAML+DB; WARN: conversation artifacts unresolved — disk copies may remain)", flush=True) else: print(f"updated: {name} status={target['status']}", flush=True) PYEOF delegate_publish_event "$DELEGATE_JOB_ID" cancelled "session stopped by operator before job completion" "$DELEGATE_JOB_TOKEN" "$DELEGATE_JOB_ATTEMPT" echo echo "=== stop complete ===" echo " session: $SESSION_NAME" echo " agent: $AGENT" echo " reason: $REASON" echo " captured: ${CAPTURED_UUID:-}" echo " purge: $PURGE${PURGE_UUID:+ (uuid $PURGE_UUID)}" echo " time: $NOW_ISO" echo echo "Recovery: multi-agent-mux-create + multi-agent-mux-resume 로 동일 컨텍스트 복원 가능" echo " (단 --purge-conversation 사용 시 복원 불가)"