Files
multi-agent-mux/.agents/skills/multi-agent-mux-resume/scripts/update_yaml_resumed.sh
T
GodopuandClaude Opus 5.5 e4c7c8fe9b fix: attach_command from one builder; no kill/start_command; stop closes a row-less session (Issue #71)
- attach_command is `herdr --session <server> agent attach <herdr name>`
  (`default` written too), built by lib_py.agents.sanitize.attach_command;
  create, resume and reconcile all use it. kill_command and start_command
  are no longer written, and status --json drops start_command.
- The two raw kill-session hints (create exit 43, id_order's orphan) print a
  stop-skill command with --herdr-session instead.
- stop_session.sh closes a session that has no registry row, herdr only and
  without --agent, when herdr runs it inside this workspace; another
  workspace's session is refused (exit 5), a missing one is exit 1, one that
  survives kill-session is exit 6. The registry is not changed.
- Docs: only the SKILL.md lines these changes made wrong; the skill block
  pins follow. Tests that asserted the removed fields keep their intent
  (issue50: create's own row; issue21: no control-root path in
  attach_command; tier2: the new form and the absent fields). S11 pins the
  shim to 4243da5, which changed it on purpose.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:16:53 +00:00

284 lines
11 KiB
Bash
Executable File

#!/usr/bin/env bash
# update_yaml_resumed.sh — multi-agent-mux-resume 의 부속 스크립트
# Resume 한 세션의 agent-sessions.yaml 엔트리를 status=running + resume 메타로 갱신.
# resume UUID 를 per-row own id (claude_session_id_own / agy_conversation_id_own)
# 에 박는다 — agent_identities 전역은 더 이상 primary 아님 (cache 로 강등, P0-C/단계 e).
#
# Usage: bash update_yaml_resumed.sh --session <name> --uuid <id> [--agent claude|agy|hermes|grok|opencode|codex]
set -euo pipefail
source "$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/lib.sh"
usage() {
cat <<EOF
Usage: $0 --session <name> --uuid <id> [--agent claude|agy|hermes|grok|opencode|codex] [--herdr-session <name>] [--cmd-full <cmd>]
--uuid may be empty for an Issue-3 Class A fresh-spawn resume (agy/hermes/
opencode/codex 0-turn stopped session, no conversation id ever assigned) - pass
--cmd-full so the display command can be recorded without a uuid to embed.
EOF
}
SESSION_NAME=""
UUID=""
AGENT=""
WORKSPACE=""
ROLE=""
HERDR_SERVER_OPT=""
HERDR_WORKSPACE_OPT=""
CMD_FULL_OPT=""
ALREADY_RUNNING=0
DROP_STALE_ID=0
while [ $# -gt 0 ]; do
case "$1" in
--session) SESSION_NAME="$2"; shift 2 ;;
--uuid) UUID="$2"; shift 2 ;;
--agent) AGENT="$2"; shift 2 ;;
--workspace) WORKSPACE="$2"; shift 2 ;;
--role) ROLE="$2"; shift 2 ;;
--herdr-session|--herdr-server) HERDR_SERVER_OPT="$2"; shift 2 ;;
--herdr-workspace) HERDR_WORKSPACE_OPT="$2"; shift 2 ;;
--cmd-full) CMD_FULL_OPT="$2"; shift 2 ;;
--already-running) ALREADY_RUNNING=1; shift ;;
--drop-stale-id) DROP_STALE_ID=1; shift ;;
-h|--help) usage; exit 0 ;;
*) echo "ERROR: unknown arg: $1" >&2; exit 2 ;;
esac
done
[ -n "$SESSION_NAME" ] || { echo "ERROR: --session required" >&2; exit 2; }
[ -f "$AGENT_SESSIONS_YAML" ] || { echo "ERROR: $AGENT_SESSIONS_YAML not found" >&2; exit 1; }
if [ -n "$HERDR_SERVER_OPT" ]; then
export HERDR_SESSION_NAME="$HERDR_SERVER_OPT"
export HERDR_SERVER_OPT_EXPLICIT="1"
else
HERDR_SESSION_NAME="$(resolve_herdr_session "$SESSION_NAME" "${WORKSPACE:-}")"
export HERDR_SESSION_NAME
export HERDR_SERVER_OPT_EXPLICIT="0"
fi
if [ -n "$HERDR_WORKSPACE_OPT" ]; then
MAM_WS_LABEL="$HERDR_WORKSPACE_OPT"
export MAM_WS_LABEL_EXPLICIT="1"
else
MAM_WS_LABEL="$(resolve_herdr_workspace "$SESSION_NAME" "${WORKSPACE:-}")"
export MAM_WS_LABEL_EXPLICIT="0"
fi
export MAM_WS_LABEL
# --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
if [ -z "$ROLE" ]; then
case "$SESSION_NAME" in
*-planner-*) ROLE="planner" ;;
*-reviewer-*) ROLE="reviewer" ;;
*) ROLE="creator" ;;
esac
fi
NOW_ISO=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
NOW_EPOCH=$(date +%s)
# 새 herdr pane pid / 자식 pid 를 bash 에서 캡처 (env 로 전달, P1-B)
PANE_PID=$(_herdr list-panes -t "$SESSION_NAME" -F '#{pane_pid}' 2>/dev/null | head -1 || true)
PANE_PID="${PANE_PID:-}"
CHILD_PID=0
if { [ "$AGENT" = "agy" ] || [ "$AGENT" = "hermes" ]; } && [ -n "$PANE_PID" ]; then
CHILD_PID=$(pgrep -P "$PANE_PID" -x "$AGENT" 2>/dev/null | head -1 || true)
CHILD_PID="${CHILD_PID:-0}"
fi
DELEGATE_JOB_ID=$(MAM_STATE_JSON="$(load_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:
print(s.get('delegate_job_id', '') or '')
sys.exit(0)
")
atomic_dump_yaml "$AGENT_SESSIONS_YAML" \
SESSION_NAME="$SESSION_NAME" UUID="$UUID" AGENT="$AGENT" NOW_ISO="$NOW_ISO" \
NOW_EPOCH="$NOW_EPOCH" TARGET_WORKSPACE="${WORKSPACE:-$WORKSPACE_ROOT}" ROLE="$ROLE" \
PANE_PID="$PANE_PID" CHILD_PID="$CHILD_PID" HERDR_SERVER_OPT_EXPLICIT="${HERDR_SERVER_OPT_EXPLICIT:-0}" \
MAM_WS_LABEL="$MAM_WS_LABEL" MAM_WS_LABEL_EXPLICIT="${MAM_WS_LABEL_EXPLICIT:-0}" \
ALREADY_RUNNING="$ALREADY_RUNNING" DROP_STALE_ID="$DROP_STALE_ID" \
CMD_FULL_OPT="$CMD_FULL_OPT" <<'PYEOF'
from lib_py.agents.sanitize import attach_command
name = os.environ['SESSION_NAME']
uuid = os.environ['UUID']
agent = os.environ['AGENT']
now = os.environ['NOW_ISO']
epoch = int(os.environ.get('NOW_EPOCH', '0') or '0')
ws_root = os.environ.get('TARGET_WORKSPACE', '') or os.environ.get('WORKSPACE_ROOT', '')
role = os.environ.get('ROLE', 'creator')
pane_pid = os.environ.get('PANE_PID', '')
target = None
for s in d.get('herdr_sessions', []):
if s.get('name') == name:
target = s
break
if target is None:
pwd = os.path.abspath(ws_root)
default_server = 'mam-' + os.path.basename(pwd).lower().replace('_', '-')
server_name = os.environ.get('HERDR_SESSION_NAME', default_server)
wsl = os.environ.get('MAM_WS_LABEL', '')
target = {
'name': name,
'status': 'running',
'role': role,
'herdr_session_created_at': now,
'herdr_session_epoch': epoch,
'herdr_session': server_name,
'herdr_server': server_name,
'herdr_workspace': wsl,
'delegate_job_id': None,
'pane': {'index': 0, 'pid': int(pane_pid) if pane_pid.isdigit() else 0, 'cmd': agent, 'cwd': ws_root},
'attach_command': attach_command(server_name, name),
}
d.setdefault('herdr_sessions', []).append(target)
else:
sn = os.environ.get('HERDR_SESSION_NAME')
is_explicit = os.environ.get('HERDR_SERVER_OPT_EXPLICIT') == '1'
if sn:
if is_explicit or not target.get('herdr_session'):
target['herdr_session'] = sn
target['herdr_server'] = sn
target['attach_command'] = attach_command(sn, name)
wsl = os.environ.get('MAM_WS_LABEL', '')
ws_explicit = os.environ.get('MAM_WS_LABEL_EXPLICIT') == '1'
if wsl and (ws_explicit or not target.get('herdr_workspace')):
target['herdr_workspace'] = wsl
target['status'] = 'running'
# Issue #21 (D11): a row keeps the control-plane binding it was created with;
# a legacy row without one gets the binding this resume used.
_cp_raw = os.environ.get('CONTROL_PLANE_JSON', '')
if _cp_raw and not isinstance(target.get('control_plane'), dict):
try:
import json as _json
_cp = _json.loads(_cp_raw)
target['control_plane'] = {k: _cp[k] for k in ('workspace_root', 'agent_sessions_yaml', 'mam_jobs_dir', 'delegate_job_logs_dir')}
except Exception:
pass
stale_dropped = ''
if not uuid and os.environ.get('DROP_STALE_ID') == '1':
from lib_py.agents.autopin import claimed_elsewhere
from lib_py.agents.registry import get_adapter
_adapter = get_adapter(agent)
_own_key = _adapter.own_key if _adapter else ''
_old = (target.get(_own_key) or '').strip() if _own_key else ''
if _old and _old not in set(claimed_elsewhere(target, d)):
target[_own_key] = None
stale_dropped = _old
if not uuid and os.environ.get('ALREADY_RUNNING') != '1':
# ISSUE-3 (challenge c4b0a075): a Class A fresh-spawn resume re-arms
# discovery from scratch - the resumed agent has not spoken yet, so any
# on-disk conversation older than THIS resume must not be auto-pinned to
# it by reconcile.sh's mode="discover" mtime >= epoch check. Without this,
# the row's watermark stays at the original create_session.sh timestamp,
# letting reconcile.sh capture a stale/unrelated transcript before the
# resumed agent's first real turn.
target['herdr_session_epoch'] = epoch
target['herdr_session_created_at'] = now
target['session_id_source'] = 'pending-discovery'
target['session_id_verified'] = False
target.pop('terminated_at', None)
target.pop('terminated_at_epoch', None)
target.pop('termination_mode', None)
target.pop('archived_at', None)
# stop 메타도 정리 — resume 하면 더 이상 stopped 상태가 아니므로 잔존 필드를 제거.
target.pop('stopped_at', None)
target.pop('stopped_at_epoch', None)
target.pop('stop_reason', None)
target.pop('resumable', None)
if uuid:
target['last_visible_status'] = f'resumed conversation {uuid} at {now}'
elif os.environ.get('ALREADY_RUNNING') == '1':
target['last_visible_status'] = f'already running; no id recorded at {now}'
elif stale_dropped:
target['last_visible_status'] = f'resumed (fresh spawn, recorded id {stale_dropped} no longer verified) at {now}'
else:
# ISSUE-3 Class A fresh-spawn resume: no conversation id existed yet.
target['last_visible_status'] = f'resumed (fresh spawn, no prior turn) at {now}'
target.setdefault('pane', {})
if pane_pid.isdigit():
target['pane']['pid'] = int(pane_pid)
if agent == 'claude':
target['pane']['cmd'] = 'claude'
target['pane']['cmd_full'] = f'claude --dangerously-skip-permissions -r {uuid}'
target['claude_session_id_own'] = uuid
elif agent == 'agy':
target['pane']['cmd'] = 'agy'
if uuid:
target['pane']['cmd_full'] = f'agy --dangerously-skip-permissions --conversation {uuid}'
target['agy_conversation_id_own'] = uuid
else:
target['pane']['cmd_full'] = os.environ.get('CMD_FULL_OPT', '') or 'agy --dangerously-skip-permissions'
cp = os.environ.get('CHILD_PID', '0')
if cp.isdigit() and int(cp) > 0:
target['child_pid'] = int(cp)
elif agent == 'hermes':
target['pane']['cmd'] = 'hermes'
if uuid:
target['pane']['cmd_full'] = f'hermes --resume {uuid}'
target['hermes_conversation_id_own'] = uuid
else:
target['pane']['cmd_full'] = os.environ.get('CMD_FULL_OPT', '') or 'hermes --yolo --accept-hooks'
cp = os.environ.get('CHILD_PID', '0')
if cp.isdigit() and int(cp) > 0:
target['child_pid'] = int(cp)
elif agent == 'grok':
target['pane']['cmd'] = 'grok'
target['pane']['cmd_full'] = f'grok --resume {uuid}'
target['grok_session_id_own'] = uuid
cp = os.environ.get('CHILD_PID', '0')
if cp.isdigit() and int(cp) > 0:
target['child_pid'] = int(cp)
elif agent == 'opencode':
target['pane']['cmd'] = 'opencode'
if uuid:
target['pane']['cmd_full'] = f'opencode --session {uuid} --auto --standalone'
target['opencode_session_id_own'] = uuid
else:
target['pane']['cmd_full'] = os.environ.get('CMD_FULL_OPT', '') or 'opencode --auto --standalone'
cp = os.environ.get('CHILD_PID', '0')
if cp.isdigit() and int(cp) > 0:
target['child_pid'] = int(cp)
elif agent == 'codex':
target['pane']['cmd'] = 'codex'
if uuid:
target['pane']['cmd_full'] = f'codex resume --dangerously-bypass-approvals-and-sandbox {uuid}'
target['codex_session_id_own'] = uuid
else:
target['pane']['cmd_full'] = os.environ.get('CMD_FULL_OPT', '') or 'codex --dangerously-bypass-approvals-and-sandbox'
cp = os.environ.get('CHILD_PID', '0')
if cp.isdigit() and int(cp) > 0:
target['child_pid'] = int(cp)
snap = d.setdefault('snapshot', {})
snap['taken_at'] = now
snap.pop('terminated_at', None)
snap.pop('terminated_at_epoch', None)
print(f"updated: {name} status=running (resume id -> per-row own id)", flush=True)
PYEOF
delegate_publish_event "$DELEGATE_JOB_ID" progress "resumed"