Files
multi-agent-mux/.agents/skills/lib_py/agents/base.py
T
GodopuandClaude Fable 5.1 c82ea75a15 fix(issue-10,11,13,15): complete agy purge, orchestrator purge, workspace-anchored registry
Issue #10 - agy purge_artifacts left resumable pieces behind: it now also
removes the SQLite sidecars (-wal/-shm/-journal), the title annotation and
the presence lock (the lock only once no live process references the
conversation), and residual_artifacts() reports anything under
~/.gemini/antigravity-cli still carrying the uuid.

Issue #13 - the orchestrator has no herdr_sessions row, so its conversation
could not be purged by any skill. `lib_py.agents purge <agent|auto> <uuid>`
resolves the adapter from what is on disk (orchestrator_uuids stores bare
uuids), refuses while a live process names the uuid (conversation_in_use:
process list minus the caller's own lineage, plus lsof), and prints what it
purged. `orc_onboard.sh --remove <uuid> --purge-conversation --yes [--agent]`
runs it before the registry update so a refusal changes nothing (exit 4
without --yes, 5 while in use).

Issue #11 - "Successfully removeed": conjugate add/remove explicitly.

Issue #15 - the job registry and audit log followed the caller's cwd, so the
pytest suite (create_session.sh with its default onboarding job, run from the
repo root) had left 593 test records in the real .mam/jobs. Defaults now
resolve MAM_JOBS_DIR / DELEGATE_JOB_LOGS_DIR, then $WORKSPACE_ROOT/.mam/...,
then the cwd (mqtt_common.default_registry_dir / get_logs_dir; registry.py,
publish_event.py, service.py, create_session.sh, stop_session.sh); the
sandbox fixture pins both. The tier suites that used to leak now leave the
real registry untouched (881 records before and after).

Tests: test_issue10_13_purge.py (13), test_issue15_registry_isolation.py (7);
T-O13 pins the corrected message; the R1 helper test and B-9 logs-dir test
now assert the workspace-anchored contract; publish_event snapshot updated.

Refs #10 #11 #13 #15

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 08:18:56 +09:00

173 lines
6.1 KiB
Python

# base.py — BaseAgentAdapter abstract base class, SpawnSpec, and DiscoveryContext
import os, json, sqlite3, shutil, subprocess
from typing import Optional, Dict, Any, List
from lib_py.paths import resolve_home
from lib_py.verify_session import verify_session_uuid, workspace_key
def conversation_in_use(uuid: str, paths=()) -> bool:
"""A live process still references the conversation (Issues #10, #13).
Either its id is on a command line other than this process's own lineage
(`claude -r <uuid>`, `agy --conversation <uuid>`, ... - the purge command
itself names the uuid, so its ancestors are excluded), or one of `paths`
is held open (lsof, where available). A purge must not touch a
conversation that is in use.
"""
try:
out = subprocess.run(["ps", "-axo", "pid=,ppid=,command="],
capture_output=True, text=True, timeout=10).stdout
except Exception:
out = ""
parents: Dict[int, int] = {}
holders: List[int] = []
for line in out.splitlines():
parts = line.split(None, 2)
if len(parts) < 2 or not (parts[0].isdigit() and parts[1].isdigit()):
continue
pid, ppid = int(parts[0]), int(parts[1])
parents[pid] = ppid
if len(parts) > 2 and uuid in parts[2]:
holders.append(pid)
if holders:
lineage = set()
p = os.getpid()
while p and p not in lineage:
lineage.add(p)
p = parents.get(p, 0)
if any(h not in lineage for h in holders):
return True
existing = [p for p in paths if p and os.path.exists(p)]
if existing and shutil.which("lsof"):
try:
r = subprocess.run(["lsof", "-t"] + existing, capture_output=True, text=True, timeout=10)
if r.stdout.strip():
return True
except Exception:
pass
return False
class SpawnSpec:
def __init__(self, agent_name: str, session_name: str, command: str, env: Optional[Dict[str, str]] = None):
self.agent_name = agent_name
self.session_name = session_name
self.command = command
self.env = env or {}
class DiscoveryContext:
def __init__(self, workspace: str, agent_name: str = "", home_dir: Optional[str] = None,
claude_dir: Optional[str] = None, epoch: int = 0,
row: Optional[Dict[str, Any]] = None, mode: str = "discover"):
self.workspace = workspace
self.agent_name = agent_name
self.home_dir = resolve_home(home_dir)
self.claude_dir = claude_dir or os.environ.get("CLAUDE_PROJECT_DIR", f"{self.home_dir}/.claude/projects")
self.epoch = epoch
self.row = row or {}
self.mode = mode
@property
def ws_key(self) -> str:
return workspace_key(self.workspace)
@property
def cwd(self) -> str:
return (self.row.get("pane", {}).get("cwd", "") if isinstance(self.row, dict) else "") or self.workspace
class BaseAgentAdapter:
@property
def name(self) -> str:
raise NotImplementedError
@property
def own_key(self) -> str:
raise NotImplementedError
@property
def ready_tokens(self) -> str:
raise NotImplementedError
@property
def exit_key(self) -> str:
raise NotImplementedError
@property
def delegate_agent_key(self) -> str:
raise NotImplementedError
@property
def identity_cache_fields(self) -> tuple:
"""agent_identities 캐시의 에이전트별 필드명.
B-10(Option A)로 캐시 읽기 경로가 제거되어 현재 생산 소비자는 0건이지만,
캐시 쓰기 경로가 도입되면 즉시 필요한 유일한 스키마 기술이므로 존치한다.
임의 삭제 금지 — 삭제 시 4개 어댑터에 필드명을 다시 흩뿌려야 한다."""
raise NotImplementedError
@property
def input_prompt(self) -> Optional[str]:
return None
@property
def input_placeholder(self) -> Optional[str]:
return None
@property
def input_rule_pattern(self) -> Optional[str]:
return None
@property
def modal_tokens(self) -> Optional[str]:
return None
@property
def strong_ready_tokens(self) -> str:
return self.ready_tokens
@property
def weak_ready_tokens(self) -> str:
return ''
def derive_session_name(self, slug: str, role: str = "creator") -> str:
r = role.lower()
return f"{slug}-{r}-{self.name}"
def matches_session_name(self, session_name: str) -> bool:
for r in ('creator', 'planner', 'reviewer'):
if session_name.endswith(f"-{r}-{self.name}"):
return True
return session_name.endswith(f"-{self.name}")
def verify_session(self, ws: str, uuid: str, row: Optional[Dict[str, Any]] = None, mode: str = "discover") -> bool:
return verify_session_uuid(ws, self.name, uuid, row=row, mode=mode)
def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str:
raise NotImplementedError
def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool:
raise NotImplementedError
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> list:
raise NotImplementedError
def residual_artifacts(self, uuid: str, ctx: DiscoveryContext) -> list:
"""Paths still carrying `uuid` after a purge. Adapters that know their
on-disk tree override this; the default has nothing to scan."""
return []
def conversation_in_use(self, uuid: str, ctx: DiscoveryContext) -> bool:
"""True while a live process still references the conversation."""
return conversation_in_use(uuid, [self.artifact_path(uuid, ctx)])
def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str:
raise NotImplementedError
def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str:
raise NotImplementedError
def auth_ok(self, run_cmd: Optional[Any] = None) -> bool:
raise NotImplementedError
def discover(self, ctx: DiscoveryContext) -> list:
raise NotImplementedError