feat(skill): implement multi-agent-mux-orc-onboard skill and orchestrator_uuids exclusion gate (40/40 PASS)

This commit is contained in:
2026-08-12 12:49:33 +09:00
parent 1e1ab8ce06
commit 6be1b6aecb
11 changed files with 1430 additions and 5 deletions
+100 -2
View File
@@ -22,6 +22,7 @@ if [ -z "${BASH_VERSION:-}" ]; then
return 1 2>/dev/null || exit 1
fi
SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PYTHONPATH="$SKILL_DIR:${PYTHONPATH:-}"
WORKSPACE_ROOT="${WORKSPACE_ROOT:-$(cd "$SKILL_DIR/../.." && pwd)}"
AGENT_SESSIONS_YAML="${AGENT_SESSIONS_YAML:-$WORKSPACE_ROOT/.mam/agent-sessions.yaml}"
@@ -992,6 +993,17 @@ def _validate(d):
if iso is not None:
if not isinstance(iso, dict) or not iso.get('uuid') or not iso.get('root'):
raise SystemExit(f"VALIDATE: herdr_sessions[{i}] {s.get('name')!r} isolation block requires uuid/root")
orc_uuids = d.get('orchestrator_uuids')
if orc_uuids is not None:
if not isinstance(orc_uuids, list):
raise SystemExit("VALIDATE: orchestrator_uuids is not a list")
seen_orc = set()
for u in orc_uuids:
if not isinstance(u, str) or not u.strip():
raise SystemExit("VALIDATE: orchestrator_uuids items must be non-empty strings")
if u in seen_orc:
raise SystemExit("VALIDATE: orchestrator_uuids contains duplicate item")
seen_orc.add(u)
def get_terminal_set(d):
return {s.get('name'): s.get('status') for s in d.get('herdr_sessions', []) if s.get('status') in ('stopped', 'terminated', 'archived')}
@@ -1003,6 +1015,10 @@ def get_all_sessions_status(d):
name = s.get('name')
ser = json.dumps(s, sort_keys=True)
res[name] = hashlib.sha256(ser.encode('utf-8')).hexdigest()
orc_uuids = d.get('orchestrator_uuids')
if orc_uuids is not None:
ser_orc = json.dumps(orc_uuids, sort_keys=True)
res['__orchestrator_uuids__'] = hashlib.sha256(ser_orc.encode('utf-8')).hexdigest()
return res
os.makedirs(os.path.dirname(db_path) or '.', exist_ok=True)
@@ -1171,6 +1187,76 @@ PYEOF
# Returns 0 if valid (passes Stage 1, 2, 3), 1 otherwise.
# ---------------------------------------------------------------------------
VERIFY_SESSION_PYTHON='
_MAM_ORC_CACHE = None
def mam_orchestrator_uuids():
global _MAM_ORC_CACHE
if _MAM_ORC_CACHE is not None:
return _MAM_ORC_CACHE
import os, sys, json, sqlite3, yaml
override = os.environ.get("MAM_ORCHESTRATOR_UUIDS")
if override is not None:
if not override.strip():
_MAM_ORC_CACHE = []
return _MAM_ORC_CACHE
if override.strip().startswith("["):
try:
parsed = json.loads(override)
if isinstance(parsed, list):
_MAM_ORC_CACHE = [str(x) for x in parsed if x]
return _MAM_ORC_CACHE
except Exception:
pass
_MAM_ORC_CACHE = [x.strip() for x in override.split(",") if x.strip()]
return _MAM_ORC_CACHE
res = []
d_obj = None
try:
if "MAM_STATE_JSON" in os.environ and os.environ.get("MAM_STATE_JSON"):
d_obj = json.loads(os.environ.get("MAM_STATE_JSON"))
except Exception:
d_obj = None
if d_obj is None or "orchestrator_uuids" not in d_obj:
yaml_p = os.environ.get("AGENT_SESSIONS_YAML") or os.environ.get("YAML_PATH")
if yaml_p:
db_p = os.path.splitext(yaml_p)[0] + ".db"
if os.path.exists(db_p):
try:
conn = sqlite3.connect(db_p, timeout=5.0)
r = conn.execute("SELECT data FROM state WHERE id=1").fetchone()
if r and r[0]:
d_obj = json.loads(r[0])
conn.close()
except Exception:
pass
if (d_obj is None or "orchestrator_uuids" not in d_obj) and os.path.exists(yaml_p):
try:
with open(yaml_p) as f:
d_obj = yaml.safe_load(f) or {}
except Exception:
pass
raw = d_obj.get("orchestrator_uuids") if isinstance(d_obj, dict) else None
if raw is not None:
if isinstance(raw, list) and all(isinstance(x, str) and x.strip() for x in raw):
res = list(raw)
else:
sys.stderr.write("WARNING: malformed orchestrator_uuids in state, disabling orchestrator exclusion gate\n")
res = []
_MAM_ORC_CACHE = res
return _MAM_ORC_CACHE
def mam_row_own_uuid(row):
if not isinstance(row, dict):
return None
for k in ["claude_session_id_own", "agy_conversation_id_own", "hermes_conversation_id_own", "cline_conversation_id_own"]:
v = row.get(k)
if v:
return v
return None
def workspace_key(path):
import os
try:
@@ -1204,6 +1290,10 @@ def verify_session_uuid(ws, agent, uuid, row=None, home_dir=None, claude_dir=Non
if workspace_key(cwd) != workspace_key(ws):
return False
if mode == "discover" and uuid in mam_orchestrator_uuids():
if uuid != mam_row_own_uuid(row):
return False
if (mode == "revalidate" and row.get("session_id_source") == "assigned"
and not row.get("session_id_verified")):
return True
@@ -1238,7 +1328,7 @@ def verify_session_uuid(ws, agent, uuid, row=None, home_dir=None, claude_dir=Non
pass
if not valid_session:
return False
if found_cwd and found_cwd != cwd:
if found_cwd and workspace_key(found_cwd) != workspace_key(cwd):
return False
except Exception:
return False
@@ -1413,8 +1503,16 @@ for s_item in d.get('herdr_sessions', []):
if val:
running_ids.add(val)
orchestrator_ids = set(mam_orchestrator_uuids())
if target:
for s_item in d.get('herdr_sessions', []):
if s_item.get('name') == target:
own = mam_row_own_uuid(s_item)
if own:
orchestrator_ids.discard(own)
def emit(u):
if u in running_ids:
if u in running_ids or u in orchestrator_ids:
return
print(u)
raise SystemExit(0)
@@ -0,0 +1,43 @@
---
name: multi-agent-mux-orc-onboard
description: Register current or specified orchestrator session UUID into agent-sessions.yaml orchestrator_uuids list to prevent sub-agent discovery capture.
---
# multi-agent-mux-orc-onboard
Registers an orchestrator session UUID into the `orchestrator_uuids` list of `.mam/agent-sessions.yaml` (and underlying state DB). This ensures that `find_workspace_uuid` and `verify_session_uuid` in `lib.sh` exclude orchestrator conversations when discovering unassigned sub-agent session UUIDs.
## Usage
```bash
.agents/skills/multi-agent-mux-orc-onboard/scripts/orc_onboard.sh [OPTIONS]
```
### Options
- `--uuid <uuid>`: Explicitly register the specified orchestrator session UUID (UUID format or cline ID format).
- `--remove <uuid>`: Remove the specified UUID from the `orchestrator_uuids` list.
- `--list`: Display all currently registered orchestrator UUIDs.
- `--no-autodetect`: Disable process ancestry auto-detection when `--uuid` is not provided.
- `--dry-run`: Output proposed changes without mutating the state registry.
## Auto-Detection Hierarchy (Rev.2)
When `--uuid` is omitted, `orc_onboard.sh` inspects the process ancestry tree of the nearest agent ancestor (`claude`, `agy`, `hermes`, `cline`) in the following order:
1. **CLI `argv`**:
- `claude -r <uuid>` / `claude --session-id <uuid>`
- `agy --conversation <uuid>`
- `cline --id <uuid>` / `cline --session-id <uuid>`
2. **Family-Matched Environment Variables**:
- `claude``CLAUDE_CODE_SESSION_ID`
- `agy``ANTIGRAVITY_CONVERSATION_ID`
- `hermes``HERMES_SESSION_ID`
- `cline``CLINE_SESSION_ID`
3. **Fallback**:
- If no valid ID matching the nearest agent family is found, exits with status 3 (`Could not detect orchestrator ID`).
## Exit Statuses
- `0`: Success (registered, removed, listed, or already present).
- `1`: Conflict — the ID is currently owned by a `running` sub-agent session row.
- `2`: Invalid arguments or malformed ID format.
- `3`: Detection failed — ID could not be determined.
@@ -0,0 +1,236 @@
#!/usr/bin/env bash
# orc_onboard.sh — Register/remove orchestrator session UUID in agent-sessions.yaml (O-4)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
# shellcheck disable=SC1091
source "$REPO_ROOT/.agents/skills/lib.sh"
MODE="add"
TARGET_UUID=""
AUTODETECT=true
DRY_RUN=false
usage() {
cat <<'EOF'
Usage: orc_onboard.sh [OPTIONS]
Options:
--uuid <uuid> Register specified orchestrator session UUID
--remove <uuid> Remove specified UUID from orchestrator_uuids list
--list List all registered orchestrator UUIDs
--no-autodetect Disable process ancestry auto-detection when --uuid is omitted
--dry-run Preview changes without updating state registry
EOF
exit 2
}
while [ $# -gt 0 ]; do
case "$1" in
--uuid)
if [ $# -lt 2 ] || [ -z "$2" ]; then usage; fi
TARGET_UUID="$2"
MODE="add"
shift 2
;;
--remove)
if [ $# -lt 2 ] || [ -z "$2" ]; then usage; fi
TARGET_UUID="$2"
MODE="remove"
shift 2
;;
--list)
MODE="list"
shift
;;
--no-autodetect)
AUTODETECT=false
shift
;;
--dry-run)
DRY_RUN=true
shift
;;
-h|--help)
usage
;;
*)
usage
;;
esac
done
is_valid_id() {
local val="$1"
local uuid_re='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
local cline_re='^[0-9]{10,}_[0-9A-Za-z]+$'
if [[ "$val" =~ $uuid_re ]] || [[ "$val" =~ $cline_re ]]; then
return 0
fi
return 1
}
detect_nearest_agent() {
if [ "${MAM_AUTODETECT_FORCE_FAIL:-0}" = "1" ]; then
return 3
fi
local curr=$$
local agent_family=""
local cmd_line=""
local detected_id=""
while [ -n "$curr" ] && [ "$curr" -gt 1 ]; do
cmd_line=$(ps -p "$curr" -o command= 2>/dev/null || true)
if [ -z "$cmd_line" ]; then
break
fi
# Extract tokens before any leading hyphen option
local tokens=()
for tok in $cmd_line; do
if [[ "$tok" =~ ^- ]]; then
break
fi
tokens+=("$tok")
done
# Check for agent family match in path tokens
local match=""
for tok in "${tokens[@]}"; do
local base
base="$(basename "$tok")"
case "$base" in
claude|agy|hermes|cline)
match="$base"
break
;;
esac
done
if [ -n "$match" ]; then
agent_family="$match"
# 1. Parse CLI argv for flags (handles both space and equals form)
case "$agent_family" in
claude)
detected_id=$(echo "$cmd_line" | grep -oE '(-r|--session-id)[[:space:]=]+[^[:space:]]+' | head -n 1 | sed -E 's/^(-r|--session-id)[[:space:]=]+//' || true)
;;
agy)
detected_id=$(echo "$cmd_line" | grep -oE '--conversation[[:space:]=]+[^[:space:]]+' | head -n 1 | sed -E 's/^--conversation[[:space:]=]+//' || true)
;;
cline)
detected_id=$(echo "$cmd_line" | grep -oE '(--id|--session-id)[[:space:]=]+[^[:space:]]+' | head -n 1 | sed -E 's/^(--id|--session-id)[[:space:]=]+//' || true)
;;
esac
if [ -n "$detected_id" ] && is_valid_id "$detected_id"; then
echo "$detected_id"
return 0
fi
# 2. Check family-matched environment variable
local env_var=""
case "$agent_family" in
claude) env_var="${CLAUDE_CODE_SESSION_ID:-}" ;;
agy) env_var="${ANTIGRAVITY_CONVERSATION_ID:-}" ;;
hermes) env_var="${HERMES_SESSION_ID:-}" ;;
cline) env_var="${CLINE_SESSION_ID:-}" ;;
esac
if [ -n "$env_var" ] && is_valid_id "$env_var"; then
echo "$env_var"
return 0
fi
# Stop at nearest agent ancestor
break
fi
curr=$(ps -p "$curr" -o ppid= 2>/dev/null | tr -d ' ' || true)
done
return 3
}
export PYTHONPATH="$REPO_ROOT/.agents/skills:${PYTHONPATH:-}"
if [ "$MODE" = "list" ]; then
python3 -c '
import sys, json
try:
d = json.loads(sys.stdin.read() or "{}")
except Exception:
d = {}
uuids = d.get("orchestrator_uuids", [])
for u in uuids:
print(u)
' <<< "$(load_state_json)"
exit 0
fi
if [ -z "$TARGET_UUID" ]; then
if [ "$AUTODETECT" = true ]; then
TARGET_UUID=$(detect_nearest_agent || true)
fi
if [ -z "$TARGET_UUID" ]; then
echo "ERROR: Could not detect orchestrator session ID." >&2
exit 3
fi
fi
if ! is_valid_id "$TARGET_UUID"; then
echo "ERROR: Invalid UUID or session ID format '$TARGET_UUID'." >&2
exit 2
fi
if [ "$MODE" = "add" ]; then
# Check if running sub-agent session row currently owns this UUID
check_owner_rc=0
python3 -c '
import sys, json
try:
d = json.loads(sys.stdin.read() or "{}")
except Exception:
d = {}
target = sys.argv[1]
for s in d.get("herdr_sessions", []):
if s.get("status") == "running":
for k in ["claude_session_id_own", "agy_conversation_id_own", "hermes_conversation_id_own", "cline_conversation_id_own"]:
if s.get(k) == target:
sys.exit(1)
sys.exit(0)
' "$TARGET_UUID" <<< "$(load_state_json)" || check_owner_rc=$?
if [ "$check_owner_rc" -eq 1 ]; then
echo "ERROR: ID '$TARGET_UUID' is currently owned by a running session." >&2
exit 1
fi
fi
if [ "$DRY_RUN" = true ]; then
echo "[dry-run] would $MODE orchestrator uuid: $TARGET_UUID"
exit 0
fi
MAM_TARGET_UUID="$TARGET_UUID" MAM_OP_MODE="$MODE" atomic_dump_yaml "$AGENT_SESSIONS_YAML" <<'PYEOF'
import os, sys, json
target = os.environ["MAM_TARGET_UUID"]
op = os.environ["MAM_OP_MODE"]
uuids = d.get("orchestrator_uuids", [])
if not isinstance(uuids, list):
uuids = []
if op == "add":
if target not in uuids:
uuids.append(target)
elif op == "remove":
uuids = [u for u in uuids if u != target]
d["orchestrator_uuids"] = uuids
PYEOF
echo "Successfully ${MODE}ed orchestrator UUID: $TARGET_UUID"