fix(codex): resolve peer-review findings R1-R6 and T1-T2

- R1: use herdr send-keys C-c for graceful stop
- R2: preserve JSONL fallback discovery when database is empty
- R3: apply workspace-scoped SQLite query before bounding results
- R4: tighten artifact validation to fail closed on missing/invalid metadata
- R5: verify actual rollout presence before reporting resumable in status
- R6: remove unconditional drift-B backend command fallback
- T1: parameterize artifact metadata regression with verified finder fixture
- T2: seed unmanaged and managed sessions in mock herdr for drift-B testing
- Add final loop review reports (100% PASS)
This commit is contained in:
Godopu committed 2026-09-06 00:18:19 +09:00
1 parent 76f10b2096
commit 47640e2fd7
10 files changed
+504 -34

No files matched your search

+75 -24
View File
@@ -73,17 +73,33 @@ class CodexAgentAdapter(BaseAgentAdapter):
return False
if ctx.epoch and os.path.getmtime(path) < ctx.epoch:
return False
found_cwd = db_cwd
if not found_cwd:
try:
with open(path) as f:
first = f.readline()
found_cwd = json.loads(first).get('payload', {}).get('cwd')
except Exception:
# Fail closed on invalid metadata or mismatched id / cwd (R4)
try:
with open(path) as f:
first = f.readline().strip()
meta = json.loads(first)
if not isinstance(meta, dict):
return False
if found_cwd and workspace_key(found_cwd) != workspace_key(ctx.cwd):
payload = meta.get('payload')
if not isinstance(payload, dict):
return False
file_id = payload.get('id')
file_cwd = payload.get('cwd')
if not file_id or file_id != uuid:
return False
if not file_cwd:
return False
if db_cwd and workspace_key(db_cwd) != workspace_key(file_cwd):
return False
target_cwd = ctx.cwd or ctx.workspace
if not target_cwd:
return False
if workspace_key(file_cwd) != workspace_key(target_cwd):
return False
return True
except Exception:
return False
return True
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> List[str]:
purged = []
@@ -126,7 +142,13 @@ class CodexAgentAdapter(BaseAgentAdapter):
return os.path.exists(f"{codex_home}/auth.json") or bool(os.environ.get('OPENAI_API_KEY'))
def discover(self, ctx: DiscoveryContext) -> List[str]:
target_ws = ctx.workspace or ctx.cwd
target_key = workspace_key(target_ws) if target_ws else ""
db = self._state_db(ctx)
candidates = []
seen = set()
if db and os.path.exists(db):
try:
conn = sqlite3.connect(db)
@@ -135,24 +157,53 @@ class CodexAgentAdapter(BaseAgentAdapter):
cols = {r[1] for r in cur.fetchall()}
order_col = "updated_at" if "updated_at" in cols else ("created_at" if "created_at" in cols else None)
order_clause = f"ORDER BY {order_col} DESC" if order_col else ""
rows = conn.execute(
f"SELECT id, cwd FROM threads {order_clause} LIMIT 50"
).fetchall()
# Query database with workspace scope before bounding (R3)
if "cwd" in cols and target_ws:
direct_cwds = list({target_ws, os.path.realpath(target_ws)})
placeholders = ",".join("?" * len(direct_cwds))
cur.execute(f"SELECT id, cwd FROM threads WHERE cwd IN ({placeholders}) {order_clause} LIMIT 50", direct_cwds)
for uuid, cwd in cur.fetchall():
if uuid and uuid not in seen and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
seen.add(uuid)
# Page through batches if needed to catch symlink aliases / canonical paths
if len(candidates) < 50:
cur.execute(f"SELECT id, cwd FROM threads {order_clause}")
while True:
batch = cur.fetchmany(100)
if not batch:
break
for uuid, cwd in batch:
if uuid in seen:
continue
if target_key and cwd and workspace_key(cwd) != target_key:
continue
if uuid and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
seen.add(uuid)
if len(candidates) >= 50:
break
if len(candidates) >= 50:
break
conn.close()
candidates = []
for uuid, cwd in rows:
if ctx.workspace and cwd and workspace_key(cwd) != workspace_key(ctx.workspace):
continue
if uuid and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
return candidates
except Exception:
pass
# R2: If database yielded usable candidates, return them; otherwise fall through to transcript discovery
if candidates:
return candidates
root = self._codex_home(ctx)
candidates = []
paths = sorted(glob.glob(f"{root}/sessions/*/*/*/rollout-*.jsonl"), key=os.path.getmtime, reverse=True)[:50]
paths = sorted(glob.glob(f"{root}/sessions/*/*/*/rollout-*.jsonl"), key=os.path.getmtime, reverse=True)
for path in paths:
uuid = os.path.basename(path)[:-6][-36:]
if uuid and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
base = os.path.basename(path)
if base.endswith(".jsonl") and len(base) >= 42:
uuid = base[:-6][-36:]
if uuid and uuid not in seen and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
seen.add(uuid)
if len(candidates) >= 50:
break
return candidates
@@ -547,10 +547,6 @@ if herdr_confirmed:
except Exception:
pass
if not agent:
if pm_check and pm_check.get('cmd') in ('claude', 'agy', 'hermes', 'grok', 'opencode', 'codex'):
agent = pm_check['cmd']
if not agent:
continue
@@ -139,8 +139,6 @@ def resume_on_disk(s):
conn.close()
if r and r[0] and os.path.exists(r[0]):
return 'yes'
if r:
return 'yes'
except Exception:
pass
m = glob.glob(f"{codex_home}/sessions/*/*/*/rollout-*-{u}.jsonl")
@@ -340,8 +338,6 @@ def resume_on_disk(s):
conn.close()
if r and r[0] and os.path.exists(r[0]):
return 'yes'
if r:
return 'yes'
except Exception:
pass
m = glob.glob(f"{codex_home}/sessions/*/*/*/rollout-*-{u}.jsonl")
@@ -198,7 +198,11 @@ graceful_stop() {
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"
send_keys_safe "$SESSION_NAME" "$exitkey" "stop$$" || echo "graceful: safe delivery failed (rc=$?) — falling back to kill chain"
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: safe delivery failed (rc=$?) — falling back to kill chain"
fi
_wait_session_gone "$SESSION_NAME" 5 || true
if ! herdr has-session -t "$SESSION_NAME" 2>/dev/null; then
echo "graceful: exited cleanly"