From 6803145b971cbdde6e6f1d1f1514e115a15d8122 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 18:25:38 -0600 Subject: [PATCH] =?UTF-8?q?claimant:=20#7770=20Phase=204=20closing=20audit?= =?UTF-8?q?=20=E2=80=94=20seam=20contract=20in=20README,=20fire-log=20unkn?= =?UTF-8?q?own=20states,=20stub-shape=20fix=20(#7772)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/opencode-claimant/README.md | 143 ++++++++++++++++++ pm-stack/opencode-claimant/claimant.py | 47 ++++-- pm-stack/opencode-claimant/prompt.md | 14 +- .../opencode-claimant/test/test_claimant.py | 30 +++- pm-stack/opencode-claimant/test_claimant.py | 48 ++++++ 5 files changed, 253 insertions(+), 29 deletions(-) diff --git a/pm-stack/opencode-claimant/README.md b/pm-stack/opencode-claimant/README.md index 0bfb2ed419..e082856d2f 100644 --- a/pm-stack/opencode-claimant/README.md +++ b/pm-stack/opencode-claimant/README.md @@ -210,6 +210,149 @@ be revisited with a count probe. No code change is made on this question — per #4916, no code change without evidence of truncation, and none exists. +## Seam Contract (#7770 — closing audit, Phase 4, 2026-11-11) + +The one contract for all three of the claimant's seams (design +#7770; Phases 1–3 are #7325/#7375/#7706, #7367/#7760, +#7356/#7366/#7732), stated beside #4916's session contract above +so it survives prompt and implementation edits: + +> **The claimant acts only on a verified read.** A read is +> verified when it arrived through the seam's one transport, in +> the shape the writer actually produces, with its status +> checked. Anything else is **UNKNOWN** — and unknown never +> authorizes a side effect (launch, delete, unbind) and is never +> recorded as a measurement. + +The three seam decisions: + +1. **Queue seam — one machine-readable channel, and the yield is + where the verb writes it.** Queue rows are read in the + broker's rich `/list` shape (see the divergence note below); + the yield of record is `progress.last_checkpoint.stage` + (#7706 option A: `progress.stage` stays accepted for older + rows, and `normalize_row` only lifts the checkpoint stage + when no live stage is set, so a live later stage vetoes a + stale yield). A row the reader cannot classify is not a + candidate. +2. **Server seam — one authenticated transport; status and shape + are the verdict.** Every OpenCode-server call in `claimant.py` + goes through `_server_request` (Basic auth, status captured + via curl's `-w` trailer); success is HTTP 2xx plus the + expected body shape. *Zero messages* is a 2xx whose `data` + list is empty; *gone* is a 404 from the per-id GET. A + subprocess exit code is never a verdict. +3. **Actuation seam — mode is a gate, sequence is verified, the + log is a measurement.** Shadow mode mutates nothing (checked + in `launch_step` itself). The landed launch order is create → + verify location → bind → verified prompt (the #7356 + resolution: a prompt that cannot be landed leaves the binding + standing for supervision, because unbinding could + double-launch over a worker that is in fact executing — this + supersedes the design text's create → prompt → bind order). + The fire log records only measured values: `cap_room` is what + `cap_step()` measured or `null`; `candidates_seen` is the + discovered list, or `null` when discovery itself failed. + +### Seam inventory (Phase 4, #7772) + +#4916's table above owns the OpenCode-server calls in `poll.py` +and the calls `prompt.md` prescribes; this inventory owns +`claimant.py`'s remaining external reads/calls and both queue +seams. Overlap is cross-referenced, never duplicated +(disposition (c)). + +| Caller | Read/call | Disposition | +|---|---|---| +| `poll.py` `_broker_post` / `_fetch_rows` | Queue-broker `POST /list` (`rich: true`, `limit=500`) for `claimed` + `handed_off` rows, token from the broker token file in an `X-Agent-Token` header | The queue seam's one read. Transport/protocol failure raises in `_broker_post`; `_fetch_rows` then contributes **no rows for that queue** — fail-closed for launches (no candidates invented), but see the recorded residual below | +| `poll.py` `normalize_row` | Lifts `last_checkpoint.stage` → `progress.stage` (only when no live stage), payload → `packet` | Writer-shape bridge for #7706 option A; pinned by `TestFetchClaimedRows` | +| `poll.py` `_server_get`, `fetch_sessions`, `fetch_active_ids` | OpenCode server GETs | Owned by #4916's inventory (rules 1–3 there); unchanged | +| `claimant.py` `run_poll` | subprocess `python3 /pm-stack/opencode-claimant/poll.py`, stdout parsed as JSON | Verified: non-zero exit or non-JSON stdout raises; the gate treats that as discovery-UNKNOWN (fixed this audit — previously logged as an empty queue). Note: runs the **primary clone's** poll.py while `_load_poll_module` loads the sibling copy for cap counting; the claimant is installed to run from the primary, so the two are the same file in practice — recorded, not changed | +| `claimant.py` `_server_request` + wrappers | All OpenCode-server calls (session GET/DELETE/POST, prompt POST, message GET) | Decision 2 transport; per-call dispositions in #4916's table. This audit fixes its header comments, which cited the contract as "decision 3" — the server seam is Decision 2 | +| `claimant.py` supervision / launch | `repo-queue bind` (recovery + launch), `repo-queue claim --handoff --platform openchamber` (sink collection) | CLI verbs with `--worker opencode-claimant`; verdicts from exit status + parsed stdout (claim prints the claimed row or `{"task": null}`). A claim/bind failure skips or stops — a binding is never improvised. Sink collection never names a task id (#8097 Rule 1) | +| `claimant.py` `_github_issue_labels` | `gh issue view --json labels` for the held-label gate (#7670) | Verified read: non-zero exit or a non-list body raises and the candidate is skipped (fail closed) | +| `claimant.py` `read_mode`, auth files, `log_fire` | Local state files (`mode`, `service-prod.json`, broker token file, `fires.jsonl`) | Local, not seam calls: a missing/unreadable mode file means `shadow`; unreadable auth means the server rejects the call and the caller fails closed; credential values are never logged. Fire-log measurement rules are Decision 3 above | + +Recorded residuals (routed to their owning follow-ups, not +silently passed): + +- **Channel divergence from Decision 1's letter.** The design + pinned the repo-queue CLI's JSON output as the one channel; + Phase 1 landed the broker rich `/list` read instead (commit + `eb1f9987eb`), and the CLI still has no JSON list mode (its + `list` verb prints the human table; verified live 2026-11-11). + The pin's intent — a machine shape, fail-closed — is met by + the rich read; the letter is not. Recorded on #7770 for the + design thread to amend or re-pin. +- **`_fetch_rows` collapses a failed queue read to an empty + queue in poll.py's output** (`claimed: 0`, no unknown marker), + although `_broker_post` itself raises. Launches stay safe (a + failed queue contributes no candidates), but poll.py's JSON + cannot say "this queue was unreadable". Owned by open issue + #8042 (fire log cannot distinguish a failed queue read from + an empty queue); this audit's gate-exit fix + (`candidates_seen: null` when discovery itself fails) closes + the distinction at the claimant's gate, and the per-queue + marker in poll.py's output remains #8042's to land. +- **Supervision's per-queue failure is a stdout warning only** + (claimant.py `supervision_step`): an unreadable queue is not + supervised that fire and the fire log does not record it. + Actions still fail closed (recovery never acts on an unread + row). Also #8042's territory; no code change here without + its fire-log schema decision. + +### Stub-shape audit (Phase 4, #7772) + +Every test stub names the writer whose shape it mirrors: + +| Suite | Stub | Writer mirrored | Verdict | +|---|---|---|---| +| `test_poll.py` | Row fixtures + `_broker_post` stub (`TestFetchClaimedRows`) | The broker's rich `/list` row (progress incl. `last_checkpoint`, payload column) and the checkpoint verb's progress shape | Conforming; fixtures cite #7706/#8192/#8234 where the shape is non-obvious | +| `test_poll.py` | Session fixtures (`TestIsActiveRoot`, `TestFetchSessions`) | The v2 server's session objects (`time`/`outcome` markers, `parentID`) and its limit-truncation behaviour | Conforming | +| `test_claimant.py` (root) | `make_fake_run` curl stub | The claimant transport's own writer: curl `-w` status trailer on every reply, rc 0 even for 401 (as `curl -s` behaves), v2 error bodies | Conforming — the docstring states the shape contract explicitly | +| `test/test_claimant.py` | `make_fake_run` curl stub | **Was:** the reader's pre-#7770 assumption (bare bodies, no status) — the #7760 defect class; 2 of its 5 tests failed against the verified transport | **Fixed this audit:** replies now carry the status trailer and the session GET answers the v2 server's 404 error body; the stub docstring names the writer | + +### Required dispositions (Phase 4, #7772) + +- **(a) Verb trio #7349 / #7355 / #7358 — INDEPENDENT of the + landed channel, per verb.** #7349 (`list`/`health` reject + `--worker`): the claimant issues no CLI `list`/`health` reads + (rows come from the broker read; gate counts come from + poll.py), so the JSON channel does not depend on it. + #7355 (Rust client does not de-chunk >32 KiB): the claimant's + broker read is its own urllib POST in `poll.py`, not the Rust + client, so the trap does not reach it. #7358 (verbs silently + default to the shadow queue): every claimant CLI call names + its queue or its task id explicitly (`claim --queue`, + `bind `), so the default is never consulted. All three + stay open as CLI-side defects in their own right. +- **(b) #7735 (claim verb targeting) — NOT a phase of #7770**, + as the design records. The claimant has no use for it: sink + collection is deliberately broker-picked (`claim --handoff`, + #8097 Rule 1); the by-id claim remains a special-case verb + for one-off revivals in `prompt.md`, not a claimant flow. +- **(c) #4916 boundary — resolved by cross-reference.** #4916 + landed first (2026-11-10; the Session Contract section above), + so its inventory owns `poll.py`'s and `prompt.md`'s server + calls, including the claimant.py rows it lists as their + implementation. This audit owns `claimant.py`'s queue/CLI/gh + reads and both queue seams; no row is duplicated. +- **(d) #6533 — re-scoped with the reason stated.** The + mechanism chain is fixed in code (rich read `eb1f9987eb`, + sink collection `1f45283f0f`, sink status `1d1b3c60a7`), but + #6533's claim is empirical — handed-off tasks actually + launching on live fires — and no live-fire evidence is in + this audit's reach. It stays open, re-scoped to that + verification, with the Phase 1 evidence recorded on it. +- **(e) `prompt.md` generation — YES, follow-up filed as + issue #8366.** The + drift class behind #7760 is live in miniature: this audit + found `prompt.md`'s CLI-path constants stale + (`~/fleet-brokers/bin/repo-queue`, twice) against + `claimant.py`'s `~/.local/bin/repo-queue`, and repaired them; + whether the prose constants are generated from the code or + pinned by a sync check is #8366's question. + ## Hard Rules diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index 9c52fc685b..d2e91d6ab0 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -75,7 +75,7 @@ def _auth_header_args() -> List[str]: # --- Verified-read server transport (#7770 Phase 2: #7367, #7760) --- # -# The seam contract (design #7770, decision 3): EVERY OpenCode server +# The seam contract (design #7770, decision 2): EVERY OpenCode server # call in this module goes through _server_request - one authenticated # transport - and every verdict is taken from the HTTP status plus the # body's shape. A curl exit code is never a verdict: curl -s exits 0 @@ -133,7 +133,7 @@ def _get_session(session_id: str): """Verified per-id session read. Returns (verdict, session): "ok" with the session dict on a 2xx carrying a session object with an id; "gone" only on a 404 from this GET (contract - decision 3: gone is a 404 verdict, never a body-shape + decision 2: gone is a 404 verdict, never a body-shape accident); "unknown" with None for every other outcome - auth failures, 5xx, transport failures and mis-shaped 2xx bodies never authorize an action.""" @@ -182,12 +182,18 @@ def ensure_state_dir() -> None: STATE_DIR.mkdir(parents=True, exist_ok=True) -def log_fire(mode: str, candidates: List[Dict], launched: List[Dict], cap_room: "int | None", skips: List[Dict]) -> None: +def log_fire(mode: str, candidates: "List[Dict] | None", launched: List[Dict], cap_room: "int | None", skips: List[Dict]) -> None: """Append a fire log entry to fires.jsonl. cap_room is the measured available-slot count, or None when the - fire exited before the cap step ran (#7732): null means unknown, - never a placeholder 0, which would read as a saturated fleet. + cap is unknown (#7732): null means unknown, never a placeholder + 0 (which would read as a saturated fleet) and never the cap + step's -1 sentinel, which is an internal return value, not a + measurement. candidates is likewise None when candidate + discovery itself failed: candidates_seen null (I could not + read) is a different state from [] (I read, and the queue was + empty) — the #7770 Phase 4 audit found the gate exit logging + the two identically. """ ensure_state_dir() @@ -306,7 +312,7 @@ def supervision_step(mode: str) -> List[Dict]: # "gone" is a 404 from the per-id GET; "unknown" # (auth failure, 5xx, transport failure, mis-shaped # body) never authorizes recovery - the task stays - # bound (#7367, #7770 decision 3). + # bound (#7367, #7770 decision 2). verdict, session = _get_session(session_id) if verdict == "unknown": continue @@ -392,26 +398,30 @@ def supervision_step(mode: str) -> List[Dict]: return recovery_candidates -def gate_step() -> bool: +def gate_step() -> Optional[bool]: """ Step 2: Gate - check if there are any unbound opencode-lane candidates. - - Returns True if there are candidates to process, False otherwise. + + Returns True if there are candidates to process, False if the + (verified) candidate list holds none, and None when discovery + itself failed: an unreadable queue is UNKNOWN, not empty + (#7770 contract — unknown never authorizes a side effect and + is never recorded as a measurement). """ try: poll_data = run_poll() candidates = poll_data.get("candidates", []) - + # Filter for unbound opencode-lane tasks unbound_opencode = [ c for c in candidates if c.get("lane") == "opencode" and not c.get("session_id") ] - + return len(unbound_opencode) > 0 except Exception as e: print(f"Gate check failed: {e}") - return False + return None def cap_step() -> int: @@ -851,19 +861,24 @@ def main(): # Step 2: Gate print("Running gate step...") has_candidates = gate_step() - + + if has_candidates is None: + print("Gate check failed: candidate discovery unknown. Exiting.") + log_fire(mode, None, [], None, [{"reason": "gate_unknown"}]) + return 1 + if not has_candidates: print("No unbound opencode-lane candidates found. Exiting.") log_fire(mode, [], [], None, [{"reason": "no_candidates"}]) return 0 - + # Step 3: Cap print("Running cap step...") cap_room = cap_step() - + if cap_room == -1: print("Warning: Could not determine cap room. Exiting.") - log_fire(mode, [], [], -1, [{"reason": "cap_unknown"}]) + log_fire(mode, [], [], None, [{"reason": "cap_unknown"}]) return 1 if cap_room <= 0: diff --git a/pm-stack/opencode-claimant/prompt.md b/pm-stack/opencode-claimant/prompt.md index e9ef5fd23a..23d09b0b7d 100644 --- a/pm-stack/opencode-claimant/prompt.md +++ b/pm-stack/opencode-claimant/prompt.md @@ -39,11 +39,11 @@ Never claim, bind, launch, or mutate a task in shadow mode. ## BACKEND OUTAGE — FALLBACK MODE (2026-11-06, code#6619) -If the queue backend is down — (or any broker +If the queue backend is down — `fleet queue health` (or any broker verb) fails with a broker/PostgREST error instead of returning state — do NOT improvise a fallback bind. Session binding is a database operation; the GitHub-native fallback protocol -(, doc/fleet/queue-fallback-mode.md in this +(see doc/fleet/queue-fallback-mode.md in this repo) deliberately has no claimant equivalent, because its claims are worked by the claiming worker itself. In an outage: record the failure in the fire log (the health error verbatim), launch @@ -59,9 +59,11 @@ outage is recoverable, a double-launch's damage is not. `repo-health-opencode-pilot`, `repo-health-openchamber-pilot`, `repo-health-nix-pilot`. - Queue CLI on this machine: `repo-queue` - (`~/fleet-brokers/bin/repo-queue`; it reaches the queue-broker - directly — pass `--worker opencode-claimant` on every verb you - use). + (`~/.local/bin/repo-queue`, the packaged fleet binary's argv0 + alias — the hand-built `~/fleet-brokers/bin` tree was retired by + the code#5362 cutover; this matches `REPO_QUEUE_CMD` in + claimant.py/poll.py — pass `--worker opencode-claimant` on every + verb you use). - Claim-model stamp (#8176): a session that picks up an item itself (a lane section's claim, or your own direct claim) names the model serving it: read your own serving leaf first with the @@ -266,7 +268,7 @@ queue task and issue>, "model": {"id": , terminal verbs (complete / park / block / fail) carrying `--execution "{\"lane\": \"opencode\", \"session_id\": \"\"}"` with the SAME session id you bound in step c. The queue CLI on - this machine is `repo-queue` (`~/fleet-brokers/bin/repo-queue`). + this machine is `repo-queue` (`~/.local/bin/repo-queue`). e. Post the launch agent-note on the issue (agent-note:v1, state=handed off) naming task id + session id. 5. Terminal states are recorded by the worker session itself via the diff --git a/pm-stack/opencode-claimant/test/test_claimant.py b/pm-stack/opencode-claimant/test/test_claimant.py index 3c98950327..9d62d77cac 100644 --- a/pm-stack/opencode-claimant/test/test_claimant.py +++ b/pm-stack/opencode-claimant/test/test_claimant.py @@ -53,7 +53,21 @@ def __init__(self, returncode=0, stdout="", stderr=""): def make_fake_run(events, *, create_rc=0, messages="[]"): """subprocess.run stub dispatching on argv shape, recording an ordered event log: ("create",) / ("bind", argv) / ("prompt", argv) - / ("messages",) / ("delete",) / ("session_get",).""" + / ("messages",) / ("delete",) / ("session_get",). + + Stub-shape audit (#7772, #7770 Phase 4): every curl reply mirrors + the writer it stands in for — the claimant's one transport + (`_server_request`) invokes curl with `-w "\\n%{http_code}"`, so a + real reply is the body plus a trailing status line, and curl -s + exits 0 even on a 401/404. This stub therefore appends the status + line to every curl body and answers rc 0 for HTTP errors; only a + transport-level create failure uses create_rc. (The pre-audit stub + returned bare bodies with no status line, which the verified + transport correctly read as UNKNOWN — the reader's-assumption + shape #7760 classed as a defect.)""" + + def reply(body, status): + return Result(0, body + "\n" + str(status)) def fake_run(cmd, **kwargs): argv = [str(part) for part in cmd] @@ -63,24 +77,26 @@ def fake_run(cmd, **kwargs): return Result(0, "{}") if argv[0] == "curl" and "-X" in argv and "DELETE" in argv: events.append(("delete",)) - return Result(0, "") + return reply("", 200) if argv[0] == "curl" and joined.rstrip().endswith("/message"): events.append(("messages",)) - return Result(0, messages) + return reply(messages, 200) if argv[0] == "curl" and joined.rstrip().endswith("/prompt"): events.append(("prompt", argv)) - return Result(0, "") + return reply("", 200) if argv[0] == "curl" and "-X" in argv and "POST" in argv: events.append(("create",)) if create_rc != 0: return Result(create_rc, "", "server unavailable") - return Result(0, json.dumps({ + return reply(json.dumps({ "id": "ses_new1", "location": {"directory": str(claimant.PRIMARY_CLONE)}, - })) + }), 200) if argv[0] == "curl" and "/api/session/" in joined: events.append(("session_get",)) - return Result(0, json.dumps({"error": "session not found"})) + # The v2 server's shape for a missing session: a 404 with + # an error body (the "gone" verdict's only lawful source). + return reply(json.dumps({"error": "session not found"}), 404) return Result(0, "") return fake_run diff --git a/pm-stack/opencode-claimant/test_claimant.py b/pm-stack/opencode-claimant/test_claimant.py index 09d133241e..9b955e96e3 100644 --- a/pm-stack/opencode-claimant/test_claimant.py +++ b/pm-stack/opencode-claimant/test_claimant.py @@ -494,6 +494,54 @@ def poll_stub(): [{"task_id": 777, "reason": "task_state_changed"}]) +class TestCapUnknownFireLog(unittest.TestCase): + def test_cap_unknown_logs_cap_room_null_not_sentinel(self): + # #7770 Phase 4 audit: cap_step's -1 is an internal unknown + # sentinel, not a measurement; the fire log must record + # cap_room null (unknown), never -1 (#7732's rule). + with tempfile.TemporaryDirectory() as tmp: + state_dir = Path(tmp) + fires = state_dir / "fires.jsonl" + with patch.object(claimant, "read_mode", return_value="live"), \ + patch.object(claimant, "run_poll", + return_value={"candidates": [dict(CANDIDATE)]}), \ + stub_claimed_rows([]), \ + patch.object(claimant, "get_active_root_session_count", + return_value=-1), \ + patch.object(claimant, "STATE_DIR", state_dir), \ + patch.object(claimant, "FIRES_FILE", fires): + self.assertEqual(claimant.main(), 1) + entries = [json.loads(line) + for line in fires.read_text().splitlines() if line] + self.assertEqual(len(entries), 1) + self.assertIsNone(entries[0]["cap_room"]) + self.assertEqual(entries[0]["skips"], [{"reason": "cap_unknown"}]) + + +class TestGateUnknownFireLog(unittest.TestCase): + def test_gate_failure_logs_candidates_unknown_not_empty(self): + # #7770 Phase 4 audit: when poll.py itself fails, the gate + # exit must record candidates_seen null (discovery UNKNOWN) + # — [] would state a verified empty queue that was never + # read (#7770's unknown rule, #7732's candidates_seen point). + with tempfile.TemporaryDirectory() as tmp: + state_dir = Path(tmp) + fires = state_dir / "fires.jsonl" + with patch.object(claimant, "read_mode", return_value="live"), \ + patch.object(claimant, "run_poll", + side_effect=RuntimeError("poll blew up")), \ + stub_claimed_rows([]), \ + patch.object(claimant, "STATE_DIR", state_dir), \ + patch.object(claimant, "FIRES_FILE", fires): + self.assertEqual(claimant.main(), 1) + entries = [json.loads(line) + for line in fires.read_text().splitlines() if line] + self.assertEqual(len(entries), 1) + self.assertIsNone(entries[0]["candidates_seen"]) + self.assertIsNone(entries[0]["cap_room"]) + self.assertEqual(entries[0]["skips"], [{"reason": "gate_unknown"}]) + + class TestGateExitFireLog(unittest.TestCase): def test_gate_exit_logs_cap_room_null_not_zero(self): # #7732: a fire that exits at the gate never ran cap_step, so