diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index dc0b737cdd..c6d5de721d 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -692,7 +692,7 @@ fn dispatch(st: &State, path: &str, req: &Value) -> Value { // broker since the binary-direct migration retired the // Python helper it used to import). let select = if req.get("rich").and_then(|r| r.as_bool()).unwrap_or(false) { - "id,queue,title,priority,status,dedupe_key,created_at,not_before,worker_id,lease_until,lane_id,attempts,max_attempts,progress" + "id,queue,title,priority,status,dedupe_key,created_at,not_before,worker_id,lease_until,lane_id,attempts,max_attempts,progress,payload" } else { "id,queue,title,priority,status,dedupe_key,created_at,not_before" }; diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 141e242011..8445811902 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -2481,7 +2481,7 @@ fn verb_list(t: &TursoBackend, req: &Value) -> Value { let rich = req.get("rich").and_then(|r| r.as_bool()).unwrap_or(false); let select = if rich { "id, queue, title, priority, status, dedupe_key, created_at, not_before, \ - worker_id, lease_until, lane_id, attempts, max_attempts, progress" + worker_id, lease_until, lane_id, attempts, max_attempts, progress, payload" } else { "id, queue, title, priority, status, dedupe_key, created_at, not_before" }; @@ -2510,7 +2510,7 @@ fn verb_list(t: &TursoBackend, req: &Value) -> Value { sql += &format!( " ORDER BY (priority IS NULL), priority ASC, created_at ASC LIMIT {limit}" ); - let json_cols: &[&str] = if rich { &["progress"] } else { &[] }; + let json_cols: &[&str] = if rich { &["progress", "payload"] } else { &[] }; match t.query_objs(&sql, &args, json_cols) { Ok(rows) => ok(json!({"rows": rows})), Err(e) => terr(e), diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index 91f4df31e4..7344c94064 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -15,6 +15,7 @@ Usage: python3 pm-stack/opencode-claimant/claimant.py """ +import base64 import json import os import subprocess @@ -45,6 +46,32 @@ REPO_QUEUE_CMD = Path.home() / ".local" / "bin" / "repo-queue" PRIMARY_CLONE = Path.home() / "git" / "code" +# OpenCode server coordinates: the standing server requires HTTP +# Basic auth (user "opencode", password in its state file — the same +# credential poll.py and the pm-dispatch client read). Calls made +# without it are rejected, so every session call below carries it. +OPENCODE_URL = os.environ.get("OPENCODE_URL", "http://127.0.0.1:13420") +AUTH_FILE = os.environ.get( + "OPENCODE_AUTH_FILE", + os.path.expanduser("~/.local/state/opencode/service-prod.json"), +) + + +def _auth_header_args() -> List[str]: + """curl args carrying the server's Basic auth, or [] when the + credential cannot be read (the server then rejects the call and + the caller fails closed). The value is never logged.""" + try: + with open(AUTH_FILE) as f: + auth = json.load(f) + password = auth.get("password") if isinstance(auth, dict) else None + if not password: + return [] + token = base64.b64encode(f"opencode:{password}".encode()).decode() + return ["-H", f"Authorization: Basic {token}"] + except Exception: + return [] + # Concurrency cap CONCURRENCY_CAP = 36 @@ -185,87 +212,79 @@ def supervision_step(mode: str) -> List[Dict]: recovery_candidates = [] - # Get all claimed opencode-lane tasks with bound session IDs + # Get all claimed opencode-lane tasks with bound session IDs. + # Rows come from poll.py's broker rich read: the repo-queue + # binary's list verb prints a human table, and json-parsing it + # silently supervised nothing (#7325). + poll = _load_poll_module() for queue in QUEUES: try: - # Use repo-queue to list tasks - result = subprocess.run( - [str(REPO_QUEUE_CMD), "list", "--queue", queue, "--status", "claimed"], - capture_output=True, - text=True, - timeout=10 - ) + for task in poll.fetch_claimed_rows(queue): + # Rich rows carry lane/session in progress; a + # flattened row carries them at top level. + prog = task.get("progress") or {} + lane = prog.get("lane") or task.get("lane") + session_id = prog.get("session_id") or task.get("session_id") + if lane == "opencode" and session_id: + + # Check if session exists and is progressing + try: + session_response = subprocess.run( + ["curl", "-s", "-m", "5", *_auth_header_args(), + f"{OPENCODE_URL}/api/session/{session_id}"], + capture_output=True, + text=True + ) + + if session_response.returncode == 0: + session = json.loads(session_response.stdout) + if isinstance(session, dict) and "data" in session: + session = session["data"] + if not isinstance(session, dict) or not session.get("id"): + # Error body, not a session object: + # the session is gone from the server. + session = None + else: + # Check for terminal state + has_terminal = any( + marker in str(session.get("outcome", "") or "") or + marker in str((session.get("time") or {}).get("idle", "") or "") + for marker in ["idle", "outcome", "completed", "failed"] + ) - if result.returncode == 0: - data = json.loads(result.stdout) - if isinstance(data, dict): - data = data.get("rows") or [] - for task in data: - if not isinstance(task, dict): + if not has_terminal: + # Session exists and is active - nothing to do + continue + # else: Session gone from server or error + except Exception: + # Could not verify session - leave bound continue - # Rich rows carry lane/session in progress; a - # flattened row carries them at top level (#4757: - # the list verb rejects --worker, so this call - # silently fetched nothing before). - prog = task.get("progress") or {} - lane = prog.get("lane") or task.get("lane") - session_id = prog.get("session_id") or task.get("session_id") - if lane == "opencode" and session_id: - - # Check if session exists and is progressing + + # Session is gone or stuck - check if recovery is possible + # Check task attempts and lease + if task.get("attempts", 0) < task.get("max_attempts", 5): + # Verify zero messages first try: - session_response = subprocess.run( - ["curl", "-s", "-m", "5", - f"http://127.0.0.1:13420/api/session/{session_id}"], + messages_response = subprocess.run( + ["curl", "-s", "-m", "5", *_auth_header_args(), + f"{OPENCODE_URL}/api/session/{session_id}/messages"], capture_output=True, text=True ) - - if session_response.returncode == 0: - session = json.loads(session_response.stdout) - if not isinstance(session, dict) or not session.get("id"): - # Error body, not a session object: - # the session is gone from the server. - session = None - else: - # Check for terminal state - has_terminal = any( - marker in str(session.get("outcome", "") or "") or - marker in str((session.get("time") or {}).get("idle", "") or "") - for marker in ["idle", "outcome", "completed", "failed"] - ) - - if not has_terminal: - # Session exists and is active - nothing to do - continue - # else: Session gone from server or error + + if messages_response.returncode == 0: + messages = json.loads(messages_response.stdout or "[]") + if isinstance(messages, dict) and "data" in messages: + messages = messages["data"] + if isinstance(messages, list) and len(messages) == 0: + recovery_candidates.append({ + "task_id": task["id"], + "session_id": session_id, + "reason": "zero_message" + }) except Exception: - # Could not verify session - leave bound - continue - - # Session is gone or stuck - check if recovery is possible - # Check task attempts and lease - if task.get("attempts", 0) < task.get("max_attempts", 5): - # Verify zero messages first - try: - messages_response = subprocess.run( - ["curl", "-s", "-m", "5", - f"http://127.0.0.1:13420/api/session/{session_id}/messages"], - capture_output=True, - text=True - ) - - if messages_response.returncode == 0: - message_count = len(json.loads(messages_response.stdout or "[]")) - if message_count == 0: - recovery_candidates.append({ - "task_id": task["id"], - "session_id": session_id, - "reason": "zero_message" - }) - except Exception: - # Could not read messages - treat as unknown state - pass + # Could not read messages - treat as unknown state + pass except Exception as e: print(f"Warning: Supervision check failed for queue {queue}: {e}") @@ -277,8 +296,8 @@ def supervision_step(mode: str) -> List[Dict]: try: # Delete the zero-message session delete_result = subprocess.run( - ["curl", "-s", "-m", "5", "-X", "DELETE", - f"http://127.0.0.1:13420/api/session/{session_id}"], + ["curl", "-s", "-m", "5", "-X", "DELETE", *_auth_header_args(), + f"{OPENCODE_URL}/api/session/{session_id}"], capture_output=True, text=True ) @@ -348,6 +367,63 @@ def cap_step() -> int: return cap_room +def _post_prompt(session_id: str, prompt: str) -> bool: + """One prompt POST; True iff the server accepted it.""" + try: + result = subprocess.run( + ["curl", "-s", "-f", "-m", "15", "-X", "POST", + "-H", "Content-Type: application/json", + *_auth_header_args(), + "-d", json.dumps({"text": prompt}), + f"{OPENCODE_URL}/api/session/{session_id}/prompt"], + capture_output=True, + text=True, + ) + return result.returncode == 0 + except Exception: + return False + + +def _get_messages(session_id: str) -> Optional[List]: + """The session's message list, or None when it cannot be read + (transport failure, non-JSON body, error object): an unreadable + session is an UNKNOWN delivery state, never an empty one.""" + try: + result = subprocess.run( + ["curl", "-s", "-m", "5", *_auth_header_args(), + f"{OPENCODE_URL}/api/session/{session_id}/messages"], + capture_output=True, + text=True, + ) + if result.returncode != 0: + return None + data = json.loads(result.stdout or "[]") + if isinstance(data, dict) and "data" in data: + data = data["data"] + return data if isinstance(data, list) else None + except Exception: + return None + + +def _send_prompt(session_id: str, prompt: str) -> bool: + """Deliver the execution prompt to a bound session. Returns True + iff the prompt is confirmed delivered. A failed POST is + reconciled before any resend (prompt.md step 4): if a message + already landed, the worker may be executing and must never be + double-prompted; only a successful reconcile that proves the + message list is EMPTY earns one resend to the same session. An + inconclusive reconcile (unreadable session) never resends — the + binding stands and the caller flags the launch instead.""" + if _post_prompt(session_id, prompt): + return True + messages = _get_messages(session_id) + if messages is None: + return False + if len(messages) > 0: + return True + return _post_prompt(session_id, prompt) + + def launch_step(mode: str, cap_room: int) -> List[Dict]: """ Step 4: Launch - create sessions and bind tasks. @@ -357,6 +433,33 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: fire log can state why a zero-launch fire launched nothing (#6865). """ + if mode != "live": + # Shadow fires observe only (#7366): report the candidates + # that WOULD launch, bounded by cap room, and mutate nothing — + # no session created, nothing bound, nothing prompted. + try: + poll_data = run_poll() + candidates = [ + c for c in poll_data.get("candidates", []) + if c.get("lane") == "opencode" + and not c.get("session_id") + and c.get("stage") in ("handed_off", "launch_failed") + ] + except Exception as e: + print(f"Shadow launch scan failed: {e}") + return [], [] + skips = [] + room = cap_room + for candidate in candidates: + if room > 0: + skips.append({"task_id": candidate["id"], + "reason": "shadow_would_launch"}) + room -= 1 + else: + skips.append({"task_id": candidate["id"], + "reason": "shadow_beyond_cap"}) + return [], skips + if cap_room <= 0: return [], [] @@ -421,29 +524,37 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: } try: - # Create session using curl (POST) + # Create session using curl (POST), with the server's + # Basic auth — unauthenticated calls are rejected. create_cmd = ["curl", "-s", "-m", "10", "-X", "POST", "-H", "Content-Type: application/json", + *_auth_header_args(), "-d", json.dumps(session_create_body), - "http://127.0.0.1:13420/api/session"] - + f"{OPENCODE_URL}/api/session"] + create_result = subprocess.run( create_cmd, capture_output=True, text=True ) - + if create_result.returncode != 0: raise RuntimeError(f"Session creation failed: {create_result.stderr}") - + session = json.loads(create_result.stdout) - session_id = session.get("id") - + if isinstance(session, dict) and "data" in session: + session = session["data"] + session_id = session.get("id") if isinstance(session, dict) else None + if not session_id: + raise RuntimeError( + f"Session creation returned no id: {create_result.stdout[:200]}") + # Verify location before proceeding if session.get("location", {}).get("directory") != str(PRIMARY_CLONE): # Wrong location - delete and skip delete_cmd = ["curl", "-s", "-m", "5", "-X", "DELETE", - f"http://127.0.0.1:13420/api/session/{session_id}"] + *_auth_header_args(), + f"{OPENCODE_URL}/api/session/{session_id}"] subprocess.run(delete_cmd, capture_output=True) skips.append({ "task_id": task_id, @@ -468,16 +579,26 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: if bind_result.returncode != 0: # Bind failed - delete session and skip delete_cmd = ["curl", "-s", "-m", "5", "-X", "DELETE", - f"http://127.0.0.1:13420/api/session/{session_id}"] + *_auth_header_args(), + f"{OPENCODE_URL}/api/session/{session_id}"] subprocess.run(delete_cmd, capture_output=True) skips.append({ "task_id": task_id, "reason": "bind_failed" }) continue - - # Step 4d: Send prompt to bound session - # The worker should use: repo-queue with --worker and the execution context + + # Step 4d: Send the execution prompt to the bound + # session (POST /api/session/{id}/prompt — the shape + # pm-dispatch's OpenCode client uses). A bound session + # that never receives its prompt is #4758's + # zero-message case (#7356), so the send is verified, + # never assumed: _send_prompt reconciles against the + # session's messages before any resend. The binding + # stands even if the prompt cannot be landed — + # supervision owns a bound-but-unprompted session, + # and unbinding here could double-launch over a + # worker that is in fact executing. prompt = f""" Execute queue task {task_id} Issue: {issue} @@ -486,19 +607,19 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: You are a build agent working on this opencode-lane task. Use --worker {worker_id} for all queue CLI operations. Heartbeat while working to keep the claim lease alive. -Finish with: complete, park, block, or fail --execution '{{...}}' +Finish with a queue terminal verb (complete, park, block, or fail) carrying --worker {worker_id} and --execution '{{"lane": "opencode", "session_id": "{session_id}"}}'. """ - - # In a real implementation, this would send the prompt via the session API - # For now, we just record the successful launch - - launched.append({ + + entry = { "task_id": task_id, "session_id": session_id, "worker_id": worker_id, "timestamp": datetime.utcnow().isoformat() + "Z" - }) - + } + if not _send_prompt(session_id, prompt): + entry["prompt_failed"] = True + launched.append(entry) + cap_room -= 1 except Exception as e: diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index c46bb7a720..e590681838 100755 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -34,11 +34,11 @@ # null when count unknown } -Read-only by construction: claimed rows come from the repo-queue -binary (`~/.local/bin/repo-queue list --queue ---status claimed` — the deployed binary's list verb rejects -`--worker`, verified 2026-11-07) and session state from GETs to the -laptop OpenCode server. The claimant treats a null cap_room as NO +Read-only by construction: claimed rows come from the queue-broker's +`/list` endpoint with `rich: true` (the same broker the repo-queue +binary fronts; the binary's list verb prints a human table, so the +JSON rows the classifiers read only exist on this route — #7325) and +session state from GETs to the laptop OpenCode server. The claimant treats a null cap_room as NO launch room: an unreadable session list or active set must never become a launch decision. @@ -84,6 +84,21 @@ # (task 12731). REPO_QUEUE_CMD = Path.home() / ".local" / "bin" / "repo-queue" PRIMARY_CLONE = Path.home() / "git" / "code" + +# Queue-broker coordinates for the rich /list read, mirroring the +# fleet client's own resolution (pkgs/fleet crates/fleet-queue +# client.rs): REPO_QUEUE_BROKER_URL or ~/.config/repo-queue/broker-url +# for the URL, REPO_QUEUE_TOKEN_FILE or ~/.config/queue-broker/token +# for the client token. The token is read at call time, travels in the +# X-Agent-Token header exactly as the binary sends it, and is never +# logged. +BROKER_URL_FILE = Path.home() / ".config" / "repo-queue" / "broker-url" +BROKER_TOKEN_FILE = Path.home() / ".config" / "queue-broker" / "token" +# One page at the broker's own maximum (LIST_LIMIT_MAX = 500 in +# client.rs). A queue's claimed set is far smaller; and a short page +# could only ever under-report candidates, never invent one. +LIST_LIMIT = 500 + OPENCODE_URL = os.environ.get("OPENCODE_URL", "http://127.0.0.1:13420") AUTH_FILE = os.environ.get( "OPENCODE_AUTH_FILE", @@ -289,26 +304,47 @@ def fetch_active_ids(): return None +def _broker_post(path, body): + """POST a JSON body to the queue-broker and return the decoded + response object. Raises on any transport, credential or protocol + failure — callers fail closed.""" + url = os.environ.get("REPO_QUEUE_BROKER_URL", "").strip() + if not url: + url = BROKER_URL_FILE.read_text().strip() + token_file = os.environ.get("REPO_QUEUE_TOKEN_FILE", "").strip() + token = Path(token_file).read_text().strip() if token_file \ + else BROKER_TOKEN_FILE.read_text().strip() + req = urllib.request.Request( + url.rstrip("/") + path, + data=json.dumps(body).encode(), + headers={"X-Agent-Token": token, + "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=30) as res: + data = json.loads(res.read() or "null") + if isinstance(data, dict) and data.get("ok") is False: + raise RuntimeError( + f"broker {path} failed: {str(data.get('error'))[:200]}") + return data + + def fetch_claimed_rows(queue): - """Claimed rows for one queue via the repo-queue binary (the route - prompt.md documents). Returns [] with a warning on any failure: a - queue that cannot be read contributes no candidates and no - stuck-bound rows, and the cap still fails closed via the session - reads, so a partial view can never cause a launch by itself.""" + """Claimed rows for one queue from the broker's rich /list. The + repo-queue binary's list verb prints a human table, and + json-parsing it read every queue as empty — the claimant was + blind from the #5362 cutover until this route was restored + (#7325/#7375). Returns [] with a warning on any failure: a queue + that cannot be read contributes no candidates and no stuck-bound + rows, and the cap still fails closed via the session reads, so a + partial view can never cause a launch by itself.""" try: - result = subprocess.run( - [str(REPO_QUEUE_CMD), "list", "--queue", queue, - "--status", "claimed"], - capture_output=True, - text=True, - timeout=30, - cwd=str(PRIMARY_CLONE), - ) - if result.returncode != 0: - print(f"Warning: Could not poll queue {queue}: " - f"{result.stderr.strip()[:200]}", file=sys.stderr) - return [] - data = json.loads(result.stdout) + data = _broker_post("/list", { + "queue": queue, + "status": "claimed", + "rich": True, + "limit": LIST_LIMIT, + }) except Exception as e: print(f"Warning: Could not poll queue {queue}: {e}", file=sys.stderr) return [] @@ -332,15 +368,37 @@ def normalize_row(row): """Ensure a claimed row carries the progress dict the classifiers read. Broker rows already do; a flattened row (lane/stage/ session_id at top level) gets its progress synthesized so either - shape classifies the same way.""" + shape classifies the same way. Two recorded shapes are lifted to + where the classifiers look for them: + + - the yield stage: the checkpoint verb records it under + progress.last_checkpoint.stage, not progress.stage (#7706); + - the packet: it rides the row's payload column, exposed here as + `packet` (a text column's string form is parsed tolerantly).""" + row = dict(row) if not isinstance(row.get("progress"), dict): - row = dict(row) row["progress"] = { "lane": row.get("lane"), "stage": row.get("stage"), "session_id": row.get("session_id"), "issue_number": row.get("issue_number") or row.get("issue"), } + else: + row["progress"] = dict(row["progress"]) + prog = row["progress"] + if not prog.get("stage"): + last = prog.get("last_checkpoint") + if isinstance(last, dict) and last.get("stage"): + prog["stage"] = last["stage"] + if row.get("packet") is None and row.get("payload") is not None: + payload = row["payload"] + if isinstance(payload, str): + try: + payload = json.loads(payload) + except ValueError: + payload = None + if isinstance(payload, dict): + row["packet"] = payload return row @@ -359,7 +417,7 @@ def _candidate_entry(row, queue): "session_id": None, "issue": issue, "issue_number": prog.get("issue_number"), - "packet": row.get("packet", {}), + "packet": row.get("packet") or {}, "attempts": row.get("attempts", 0), "max_attempts": row.get("max_attempts", 5), "title": row.get("title"), diff --git a/pm-stack/opencode-claimant/test_claimant.py b/pm-stack/opencode-claimant/test_claimant.py index 35af05516e..8fea69831d 100644 --- a/pm-stack/opencode-claimant/test_claimant.py +++ b/pm-stack/opencode-claimant/test_claimant.py @@ -4,11 +4,16 @@ Run: python3 -m unittest pm-stack/opencode-claimant/test_claimant.py The transport (curl to the OpenCode server) and the queue CLI -(repo-queue) are stubbed at subprocess.run, and poll discovery is -stubbed at claimant.run_poll, so the suite exercises the real step -logic with no server and no queue: +(repo-queue) are stubbed at subprocess.run, poll discovery is +stubbed at claimant.run_poll, and supervision's claimed rows are +stubbed at the poll module's fetch_claimed_rows, so the suite +exercises the real step logic with no server and no queue: -- launch_step launches and binds a valid handed_off candidate; +- launch_step launches, binds and prompts a valid handed_off + candidate; a prompt that cannot be landed flags the launch entry + instead of reading as a clean launch; +- launch_step in shadow mode mutates nothing and records the + would-launch window as skips (#7366); - launch_step records a skip (not silence) when a candidate's state changes before launch, and main() writes those skips into the fires.jsonl entry; @@ -44,29 +49,21 @@ def __init__(self, returncode=0, stdout="", stderr=""): self.stderr = stderr -def make_fake_run(binds, *, session_get="gone", messages="[]"): +def make_fake_run(binds, *, session_get="gone", messages="[]", + prompt_rc=0, prompts=None): """Build a subprocess.run stub dispatching on argv shape. binds: list collecting every repo-queue bind argv. session_get: "gone" -> the session GET returns an error body (what curl -s prints for a 404); "active" -> a live session. + prompt_rc: return code for the prompt POST (curl -f fails on + HTTP errors, so 1 models a rejected prompt send). + prompts: optional list collecting every prompt POST argv. """ def fake_run(cmd, **kwargs): argv = [str(part) for part in cmd] joined = " ".join(argv) - if "repo-queue" in argv[0] and "list" in argv: - queue = argv[argv.index("--queue") + 1] - if queue == claimant.QUEUES[0]: - rows = [{ - "id": 4242, - "attempts": 0, - "max_attempts": 5, - "progress": {"lane": "opencode", "session_id": "ses_gone"}, - }] - else: - rows = [] - return Result(0, json.dumps(rows)) if "repo-queue" in argv[0] and "bind" in argv: binds.append(cmd) return Result(0, "{}") @@ -74,6 +71,10 @@ def fake_run(cmd, **kwargs): return Result(0, "") if argv[0] == "curl" and joined.rstrip().endswith("/messages"): return Result(0, messages) + if argv[0] == "curl" and joined.rstrip().endswith("/prompt"): + if prompts is not None: + prompts.append(cmd) + return Result(prompt_rc, "") if argv[0] == "curl" and "-X" in argv and "POST" in argv: return Result(0, json.dumps({ "id": "ses_new1", @@ -91,6 +92,26 @@ def fake_run(cmd, **kwargs): return fake_run +BOUND_ROW = { + "id": 4242, + "attempts": 0, + "max_attempts": 5, + "progress": {"lane": "opencode", "session_id": "ses_gone"}, +} + + +def stub_claimed_rows(rows): + """Patch the poll module's broker read (supervision's row source) + to serve `rows` for the first queue and [] for the rest.""" + poll_mod = claimant._load_poll_module() + + def fake_fetch(queue): + return list(rows) if queue == claimant.QUEUES[0] else [] + + return patch.object(poll_mod, "fetch_claimed_rows", + side_effect=fake_fetch) + + CANDIDATE = { "id": 777, "lane": "opencode", @@ -136,11 +157,72 @@ def poll_stub(): self.assertEqual(launched, []) self.assertEqual(skips, [{"task_id": 777, "reason": "task_state_changed"}]) + def test_shadow_mode_launches_nothing(self): + # #7366: a shadow fire must not create, bind or prompt — the + # candidate is reported as a would-launch skip only. + binds = [] + with patch.object(claimant, "run_poll", + return_value={"candidates": [dict(CANDIDATE)]}), \ + patch.object(claimant.subprocess, "run", make_fake_run(binds)): + launched, skips = claimant.launch_step("shadow", 3) + self.assertEqual(launched, []) + self.assertEqual(skips, [{"task_id": 777, + "reason": "shadow_would_launch"}]) + self.assertEqual(binds, []) + + def test_failed_prompt_flags_the_launch(self): + # #7356: the prompt POST is rejected and no message landed — + # the launch is recorded, but flagged, never read as clean. + binds = [] + with patch.object(claimant, "run_poll", + return_value={"candidates": [dict(CANDIDATE)]}), \ + patch.object(claimant.subprocess, "run", + make_fake_run(binds, prompt_rc=1)): + launched, skips = claimant.launch_step("live", 3) + self.assertEqual(skips, []) + self.assertEqual(len(launched), 1) + self.assertEqual(launched[0].get("prompt_failed"), True) + self.assertEqual(len(binds), 1) + + def test_landed_prompt_despite_post_error_is_clean(self): + # The POST's response was lost but the message landed: the + # reconcile read sees it and no resend/flag happens. + binds = [] + with patch.object(claimant, "run_poll", + return_value={"candidates": [dict(CANDIDATE)]}), \ + patch.object(claimant.subprocess, "run", + make_fake_run(binds, prompt_rc=1, + messages='[{"id": "m1"}]')): + launched, skips = claimant.launch_step("live", 3) + self.assertEqual(skips, []) + self.assertEqual(len(launched), 1) + self.assertNotIn("prompt_failed", launched[0]) + + def test_unreadable_session_is_never_resent(self): + # The POST failed and the reconcile read is unusable (error + # body, not a message list): delivery state is unknown, so + # no second POST may go out — the worker might be executing + # the first one. The launch is flagged instead. + binds = [] + prompts = [] + with patch.object(claimant, "run_poll", + return_value={"candidates": [dict(CANDIDATE)]}), \ + patch.object(claimant.subprocess, "run", + make_fake_run(binds, prompt_rc=1, + messages='{"error": "boom"}', + prompts=prompts)): + launched, skips = claimant.launch_step("live", 3) + self.assertEqual(skips, []) + self.assertEqual(len(launched), 1) + self.assertEqual(launched[0].get("prompt_failed"), True) + self.assertEqual(len(prompts), 1) + class TestSupervisionStep(unittest.TestCase): def test_gone_zero_message_session_is_recovered(self): binds = [] - with patch.object(claimant.subprocess, "run", make_fake_run(binds)): + with stub_claimed_rows([BOUND_ROW]), \ + patch.object(claimant.subprocess, "run", make_fake_run(binds)): recovered = claimant.supervision_step("live") self.assertEqual(recovered, [{ "task_id": 4242, @@ -154,7 +236,8 @@ def test_gone_zero_message_session_is_recovered(self): def test_active_session_is_left_bound(self): binds = [] - with patch.object(claimant.subprocess, "run", + with stub_claimed_rows([BOUND_ROW]), \ + patch.object(claimant.subprocess, "run", make_fake_run(binds, session_get="active")): recovered = claimant.supervision_step("live") self.assertEqual(recovered, []) @@ -182,6 +265,7 @@ def poll_stub(): fires = state_dir / "fires.jsonl" with patch.object(claimant, "read_mode", return_value="live"), \ patch.object(claimant, "run_poll", side_effect=poll_stub), \ + stub_claimed_rows([]), \ patch.object(claimant, "get_active_root_session_count", return_value=0), \ patch.object(claimant.subprocess, "run", make_fake_run([])), \ diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py index c59eac94e3..0f8761fe16 100755 --- a/pm-stack/opencode-claimant/test_poll.py +++ b/pm-stack/opencode-claimant/test_poll.py @@ -297,33 +297,28 @@ def test_unbound_or_direct_lane_is_not_stuck(self): class TestFetchClaimedRows(unittest.TestCase): - """Claimed rows come from the repo-queue binary (#5419 replaced - the broker-HTTP read this suite originally pinned when it was - written against the pre-#5419 poll.py). subprocess.run is - stubbed; no queue is touched. A queue that cannot be read - contributes no rows: fetch_claimed_rows returns [] on any CLI + """Claimed rows come from the queue-broker's rich /list (#7325: + the repo-queue binary's list verb prints a human table, and + json-parsing it read every queue as empty). _broker_post is + stubbed; no broker is touched. A queue that cannot be read + contributes no rows: fetch_claimed_rows returns [] on any broker or payload failure.""" - class Result: - def __init__(self, returncode=0, stdout="", stderr=""): - self.returncode = returncode - self.stdout = stdout - self.stderr = stderr - - def fetch(self, payload, returncode=0): + def fetch(self, payload, raises=None): captured = {} - def fake_run(cmd, **kwargs): - captured["cmd"] = cmd - captured["kwargs"] = kwargs - stdout = payload if isinstance(payload, str) else json.dumps(payload) - return self.Result(returncode, stdout) + def fake_post(path, body): + captured["path"] = path + captured["body"] = body + if raises is not None: + raise raises + return payload - with patch.object(poll.subprocess, "run", side_effect=fake_run): + with patch.object(poll, "_broker_post", side_effect=fake_post): rows = poll.fetch_claimed_rows("repo-health-code-pilot") return rows, captured - def test_cli_list_reads_claimed_rows_and_normalizes(self): + def test_broker_list_reads_claimed_rows_and_normalizes(self): raw = { "id": 42, "queue": "repo-health-code-pilot", @@ -331,39 +326,74 @@ def test_cli_list_reads_claimed_rows_and_normalizes(self): "worker_id": "repo-worker", "progress": {"lane": "opencode", "stage": "handed_off"}, } - rows, captured = self.fetch({"rows": [raw]}) + rows, captured = self.fetch({"ok": True, "rows": [raw]}) self.assertEqual(len(rows), 1) self.assertEqual(rows[0]["id"], 42) self.assertEqual(rows[0]["progress"]["stage"], "handed_off") - cmd = [str(part) for part in captured["cmd"]] + self.assertEqual(captured["path"], "/list") self.assertEqual( - cmd[1:], - ["list", "--queue", "repo-health-code-pilot", - "--status", "claimed"], + captured["body"], + {"queue": "repo-health-code-pilot", "status": "claimed", + "rich": True, "limit": poll.LIST_LIMIT}, ) def test_flattened_row_gets_progress_synthesized(self): - rows, _ = self.fetch([{ + rows, _ = self.fetch({"rows": [{ "id": 7, "status": "claimed", "lane": "opencode", "stage": "handed_off", "session_id": None, - }]) + }]}) self.assertEqual(len(rows), 1) self.assertEqual(rows[0]["progress"]["lane"], "opencode") self.assertEqual(rows[0]["progress"]["stage"], "handed_off") + def test_stage_lifted_from_last_checkpoint(self): + # #7706: the checkpoint verb records the yield under + # progress.last_checkpoint.stage; the classifiers read + # progress.stage. The lifted row must classify as a candidate. + rows, _ = self.fetch({"rows": [{ + "id": 9, + "status": "claimed", + "progress": {"lane": "opencode", + "last_checkpoint": {"stage": "handed_off"}}, + }]}) + self.assertEqual(len(rows), 1) + self.assertEqual(rows[0]["progress"]["stage"], "handed_off") + self.assertTrue(poll.is_candidate(rows[0])) + + def test_packet_lifted_from_payload(self): + packet = {"kind": "fix", "repo": "developing-today/code", + "issue": 1234} + rows, _ = self.fetch({"rows": [{ + "id": 11, "status": "claimed", "payload": packet, + "progress": {"lane": "opencode", "stage": "handed_off"}, + }]}) + self.assertEqual(rows[0]["packet"], packet) + entry = poll._candidate_entry(rows[0], "repo-health-code-pilot") + self.assertEqual(entry["packet"], packet) + + def test_packet_lifted_from_payload_string(self): + rows, _ = self.fetch({"rows": [{ + "id": 12, "status": "claimed", + "payload": "{\"kind\": \"triage\"}", + "progress": {"lane": "opencode", "stage": "handed_off"}, + }]}) + self.assertEqual(rows[0]["packet"], {"kind": "triage"}) + def test_empty_list_is_a_valid_empty_queue(self): - rows, _ = self.fetch({"rows": []}) + rows, _ = self.fetch({"ok": True, "rows": []}) self.assertEqual(rows, []) - def test_cli_failure_returns_no_rows(self): - rows, _ = self.fetch("", returncode=1) + def test_broker_failure_returns_no_rows(self): + rows, _ = self.fetch(None, raises=RuntimeError("broker down")) self.assertEqual(rows, []) def test_malformed_payload_returns_no_rows(self): - rows, _ = self.fetch("this is not json") + rows, _ = self.fetch({"ok": True, "rows": "not a list"}) + self.assertEqual(rows, []) + rows, _ = self.fetch({"ok": True}) self.assertEqual(rows, []) def test_non_dict_and_unclaimed_rows_are_skipped(self):