feat(a4,c3b): complete A-4 Phase 2 agent knowledge migration & Option B isolation removal

- Option B / C-3b: Deprecate isolation.root and remove its 4 legacy consumers in lib.sh, workspace_uuid.py, verify_session.py, and stop_session.sh.
- M2~M7 Migration: Implement artifact_path, verify_artifact, purge_artifacts, spawn_spec, resume_spec, auth_ok, discover, ready_tokens, exit_key, and delegate_agent_key across BaseAgentAdapter and all 4 adapters (Claude, Agy, Hermes, Cline).
- Migrate shell duplications in lib.sh, create_session.sh, resume_session.sh, stop_session.sh, and reconcile.sh to python -m lib_py.agents facts.
- Hardening & Corrections: Fix Cline resume_spec flag to '-i --id', apply shlex.quote across all facts variables with MAM_ prefix, add safe fallback in wait_for_tui_ready.
- Add comprehensive contract tests in tests/test_a4_adapter_contract.py and sync IMPROVEMENTS.md / LOG.md.
- Verified: 100% PASS across unit, component, contract, and integration tests.
This commit is contained in:
2026-08-16 23:15:24 +09:00
parent 971f14ad3f
commit b4821fafa8
21 changed files with 904 additions and 531 deletions
+10 -6
View File
@@ -1,6 +1,6 @@
# __main__.py — CLI bridge for lib_py.agents facts and resolution (N4)
import sys, json
import sys, json, shlex
from lib_py.agents.registry import get_adapter, own_key, agent_of_row
def main():
@@ -16,11 +16,15 @@ def main():
print(f"ERROR: Unknown agent {agent_name!r}", file=sys.stderr)
sys.exit(1)
# Emit shell-eval friendly facts
print(f"AGENT_NAME={adapter.name}")
print(f"OWN_KEY={adapter.own_key}")
print(f"INPUT_PROMPT={adapter.input_prompt or ''}")
print(f"INPUT_PLACEHOLDER={adapter.input_placeholder or ''}")
print(f"INPUT_RULE_PATTERN={adapter.input_rule_pattern or ''}")
q = shlex.quote
print(f"MAM_AGENT_NAME={q(adapter.name)}")
print(f"MAM_OWN_KEY={q(adapter.own_key)}")
print(f"MAM_INPUT_PROMPT={q(adapter.input_prompt or '')}")
print(f"MAM_INPUT_PLACEHOLDER={q(adapter.input_placeholder or '')}")
print(f"MAM_INPUT_RULE_PATTERN={q(adapter.input_rule_pattern or '')}")
print(f"MAM_READY_TOKENS={q(adapter.ready_tokens)}")
print(f"MAM_EXIT_KEY={q(adapter.exit_key)}")
print(f"MAM_DELEGATE_AGENT_KEY={q(adapter.delegate_agent_key)}")
elif cmd == 'resolve':
name = sys.argv[2] if len(sys.argv) > 2 else ''
+87 -3
View File
@@ -1,6 +1,6 @@
# agy.py — Antigravity (agy) agent adapter
from lib_py.agents.base import BaseAgentAdapter
import os, json, sqlite3, shutil
from typing import Optional, Any
from lib_py.agents.base import BaseAgentAdapter, DiscoveryContext
class AgyAgentAdapter(BaseAgentAdapter):
@property
@@ -11,6 +11,22 @@ class AgyAgentAdapter(BaseAgentAdapter):
def own_key(self) -> str:
return 'agy_conversation_id_own'
@property
def ready_tokens(self) -> str:
return 'Antigravity'
@property
def exit_key(self) -> str:
return 'Exit'
@property
def delegate_agent_key(self) -> str:
return 'antigravity-cli'
@property
def identity_cache_fields(self) -> tuple:
return ('conversation_id', 'conversation_db', 'conversation_brain_dir')
@property
def input_prompt(self) -> str:
return '>'
@@ -22,3 +38,71 @@ class AgyAgentAdapter(BaseAgentAdapter):
@property
def input_rule_pattern(self) -> str:
return '{10,}'
def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str:
return f"{ctx.home_dir}/.gemini/antigravity-cli/conversations/{uuid}.db"
def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool:
path = self.artifact_path(uuid, ctx)
if not os.path.exists(path):
return False
if ctx.epoch and os.path.getmtime(path) < ctx.epoch:
return False
if ctx.mode == "discover":
lc = f"{ctx.home_dir}/.gemini/antigravity-cli/cache/last_conversations.json"
cache_match = False
if os.path.exists(lc):
try:
with open(lc) as f:
lc_data = json.load(f)
cache_match = (lc_data.get(ctx.cwd) == uuid)
except Exception:
cache_match = False
if not cache_match:
if uuid in (ctx.row.get("_sibling_claimed_uuids") or []):
return False
try:
conn = sqlite3.connect(path)
r = conn.execute("SELECT count(*) FROM steps").fetchone()
conn.close()
if not r or r[0] < 1:
return False
except Exception:
return False
return True
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> list:
purged = []
db = self.artifact_path(uuid, ctx)
if os.path.exists(db):
os.remove(db)
purged.append(db)
brain = f"{ctx.home_dir}/.gemini/antigravity-cli/brain/{uuid}"
if os.path.isdir(brain):
shutil.rmtree(brain, ignore_errors=True)
purged.append(brain)
return purged
def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str:
return f"{binary} --dangerously-skip-permissions"
def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str:
if materialized and session_uuid:
return f"{binary} --dangerously-skip-permissions --conversation {session_uuid}"
return f"{binary} --dangerously-skip-permissions"
def auth_ok(self, run_cmd: Optional[Any] = None) -> bool:
home = os.environ.get("HOME_DIR") or os.environ.get("HOME") or os.path.expanduser("~")
return os.path.exists(f"{home}/.gemini/oauth_creds.json") or os.path.exists(f"{home}/.gemini/antigravity-cli/antigravity-oauth-token")
def discover(self, ctx: DiscoveryContext) -> list:
lc = f"{ctx.home_dir}/.gemini/antigravity-cli/cache/last_conversations.json"
if os.path.exists(lc):
try:
with open(lc) as f:
cand = json.load(f).get(ctx.workspace)
if cand and self.verify_artifact(cand, ctx):
return [cand]
except Exception:
pass
return []
+100 -3
View File
@@ -1,6 +1,7 @@
# claude.py — Claude Code agent adapter
from lib_py.agents.base import BaseAgentAdapter
import os, json, glob, subprocess
from typing import Optional, Any
from lib_py.agents.base import BaseAgentAdapter, DiscoveryContext
from lib_py.verify_session import workspace_key
class ClaudeAgentAdapter(BaseAgentAdapter):
@property
@@ -11,6 +12,22 @@ class ClaudeAgentAdapter(BaseAgentAdapter):
def own_key(self) -> str:
return 'claude_session_id_own'
@property
def ready_tokens(self) -> str:
return 'Anthropic|Assistant|Chat|Welcome'
@property
def exit_key(self) -> str:
return '/exit'
@property
def delegate_agent_key(self) -> str:
return 'claude-code'
@property
def identity_cache_fields(self) -> tuple:
return ('session_id', 'session_jsonl', 'session_size_bytes', 'session_lines')
@property
def input_prompt(self) -> str:
return ''
@@ -22,3 +39,83 @@ class ClaudeAgentAdapter(BaseAgentAdapter):
@property
def input_rule_pattern(self) -> str:
return '{10,}'
def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str:
return f"{ctx.claude_dir}/{ctx.ws_key}/{uuid}.jsonl"
def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool:
path = self.artifact_path(uuid, ctx)
if not os.path.exists(path):
return False
if ctx.epoch and os.path.getmtime(path) < ctx.epoch:
return False
try:
valid_session = False
found_cwd = None
with open(path) as f:
for _ in range(50):
line = f.readline()
if not line:
break
line = line.strip()
if not line:
continue
try:
payload = json.loads(line)
if payload.get("sessionId") == uuid:
valid_session = True
if payload.get("cwd"):
found_cwd = payload.get("cwd")
break
except Exception:
pass
if not valid_session:
return False
if found_cwd and workspace_key(found_cwd) != workspace_key(ctx.cwd):
return False
except Exception:
return False
return True
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> list:
jsonl = self.artifact_path(uuid, ctx)
if os.path.exists(jsonl):
os.remove(jsonl)
return [jsonl]
return []
def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str:
if use_wrapper or not session_uuid:
return f"{binary} --dangerously-skip-permissions"
return f"{binary} --dangerously-skip-permissions --session-id {session_uuid}"
def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str:
if materialized and session_uuid:
return f"{binary} --dangerously-skip-permissions -r {session_uuid}"
elif session_uuid:
return f"{binary} --dangerously-skip-permissions --session-id {session_uuid}"
return f"{binary} --dangerously-skip-permissions"
def auth_ok(self, run_cmd: Optional[Any] = None) -> bool:
if run_cmd is not None:
try:
rc, stdout, stderr = run_cmd(['claude', 'auth', 'status'])
return rc == 0 and ('"loggedIn":true' in (stdout or '').replace(' ', ''))
except Exception:
return False
try:
res = subprocess.run(['claude', 'auth', 'status'], capture_output=True, text=True)
return res.returncode == 0 and ('"loggedIn":true' in (res.stdout or '').replace(' ', ''))
except Exception:
return False
def discover(self, ctx: DiscoveryContext) -> list:
key = workspace_key(ctx.workspace)
proj = f"{ctx.claude_dir}/{key}"
candidates = []
if os.path.isdir(proj):
for j in sorted(glob.glob(f"{proj}/*.jsonl"), key=os.path.getmtime, reverse=True):
cand = os.path.basename(j)[:-6]
if cand and self.verify_artifact(cand, ctx):
candidates.append(cand)
return candidates
+79 -3
View File
@@ -1,6 +1,7 @@
# cline.py — Cline agent adapter
from lib_py.agents.base import BaseAgentAdapter
import os, json, shutil, glob
from typing import Optional, Any
from lib_py.agents.base import BaseAgentAdapter, DiscoveryContext
from lib_py.verify_session import workspace_key
class ClineAgentAdapter(BaseAgentAdapter):
@property
@@ -11,6 +12,22 @@ class ClineAgentAdapter(BaseAgentAdapter):
def own_key(self) -> str:
return 'cline_conversation_id_own'
@property
def ready_tokens(self) -> str:
return 'Cline|history|Chat|What can I do|slash commands'
@property
def exit_key(self) -> str:
return '/exit'
@property
def delegate_agent_key(self) -> str:
return 'cline-agent'
@property
def identity_cache_fields(self) -> tuple:
return ('session_id',)
@property
def input_prompt(self) -> str:
return ''
@@ -22,3 +39,62 @@ class ClineAgentAdapter(BaseAgentAdapter):
@property
def input_rule_pattern(self) -> str:
return '{10,}'
def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str:
return f"{ctx.home_dir}/.cline/data/sessions/{uuid}/{uuid}.json"
def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool:
path = self.artifact_path(uuid, ctx)
if not os.path.exists(path):
return False
if ctx.epoch and os.path.getmtime(path) < ctx.epoch:
return False
try:
with open(path) as f:
sdata = json.load(f)
if sdata.get("session_id") != uuid:
return False
found_cwd = sdata.get("cwd") or sdata.get("workspace_root")
if found_cwd and workspace_key(found_cwd) != workspace_key(ctx.cwd):
return False
except Exception:
return False
return True
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> list:
purged = []
sessions_dir = f"{ctx.home_dir}/.cline/data/sessions/{uuid}"
if os.path.isdir(sessions_dir):
shutil.rmtree(sessions_dir)
purged.append(sessions_dir)
return purged
def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str:
return f"{binary} -i"
def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str:
if materialized and session_uuid:
return f"{binary} -i --id {session_uuid}"
return f"{binary} -i"
def auth_ok(self, run_cmd: Optional[Any] = None) -> bool:
return True
def discover(self, ctx: DiscoveryContext) -> list:
sessions_dir = f"{ctx.home_dir}/.cline/data/sessions"
if os.path.isdir(sessions_dir):
files = []
for folder in glob.glob(f"{sessions_dir}/*"):
if os.path.isdir(folder):
fn = os.path.basename(folder)
jf = f"{folder}/{fn}.json"
if os.path.exists(jf):
files.append(jf)
files.sort(key=os.path.getmtime, reverse=True)
candidates = []
for j in files:
cand = os.path.basename(j)[:-5]
if cand and self.verify_artifact(cand, ctx):
candidates.append(cand)
return candidates
return []
@@ -1,6 +1,7 @@
# hermes.py — Hermes agent adapter
from lib_py.agents.base import BaseAgentAdapter
import os, sys, sqlite3
from typing import Optional, Any
from lib_py.agents.base import BaseAgentAdapter, DiscoveryContext
from lib_py.verify_session import workspace_key
class HermesAgentAdapter(BaseAgentAdapter):
@property
@@ -10,3 +11,86 @@ class HermesAgentAdapter(BaseAgentAdapter):
@property
def own_key(self) -> str:
return 'hermes_conversation_id_own'
@property
def ready_tokens(self) -> str:
return 'Hermes'
@property
def exit_key(self) -> str:
return '/exit'
@property
def delegate_agent_key(self) -> str:
return 'hermes-agent'
@property
def identity_cache_fields(self) -> tuple:
return ('session_id',)
def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str:
return f"{ctx.home_dir}/.hermes/sessions/session_{uuid}.json"
def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool:
hdb = f"{ctx.home_dir}/.hermes/state.db"
if not os.path.exists(hdb):
return False
if ctx.epoch and os.path.getmtime(hdb) < ctx.epoch:
return False
try:
conn = sqlite3.connect(hdb)
r = conn.execute("SELECT cwd FROM sessions WHERE id=?", (uuid,)).fetchone()
conn.close()
if not r:
return False
found_cwd = r[0]
if found_cwd and workspace_key(found_cwd) != workspace_key(ctx.cwd):
return False
except Exception:
return False
return True
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> list:
purged = []
json_file = self.artifact_path(uuid, ctx)
if os.path.exists(json_file):
os.remove(json_file)
purged.append(json_file)
hdb = f"{ctx.home_dir}/.hermes/state.db"
if os.path.exists(hdb):
try:
conn = sqlite3.connect(hdb)
conn.execute("DELETE FROM sessions WHERE id=?", (uuid,))
conn.execute("DELETE FROM messages WHERE session_id=?", (uuid,))
conn.commit()
conn.close()
purged.append(f"db records for session: {uuid}")
except Exception as e:
sys.stderr.write(f"WARN: purge hermes db records failed: {e}\n")
return purged
def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str:
return binary
def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str:
if materialized and session_uuid:
return f"{binary} --resume {session_uuid}"
return binary
def auth_ok(self, run_cmd: Optional[Any] = None) -> bool:
return True
def discover(self, ctx: DiscoveryContext) -> list:
hdb = f"{ctx.home_dir}/.hermes/state.db"
if os.path.exists(hdb):
try:
conn = sqlite3.connect(hdb)
r = conn.execute("SELECT id FROM sessions WHERE cwd=? ORDER BY started_at DESC LIMIT 1", (ctx.workspace,)).fetchone()
conn.close()
if r:
cand = r[0]
if cand and self.verify_artifact(cand, ctx):
return [cand]
except Exception:
pass
return []
+52 -1
View File
@@ -13,10 +13,24 @@ class SpawnSpec:
self.env = env or {}
class DiscoveryContext:
def __init__(self, workspace: str, agent_name: str, home_dir: Optional[str] = None):
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
@@ -27,6 +41,22 @@ class BaseAgentAdapter:
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:
raise NotImplementedError
@property
def input_prompt(self) -> Optional[str]:
return None
@@ -51,3 +81,24 @@ class BaseAgentAdapter:
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 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