From c79ddfc2a82629423ee03c79a1ae7a94edfca56b Mon Sep 17 00:00:00 2001 From: Ryan Weiss <1996129+rymiwe@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:17:32 -0800 Subject: [PATCH 1/3] poteto-judge: one other-family judge call per decision card, sharing true-check's principles and never-gated list Ports Practice Paul's poteto-lean prototype (rubric v1 verbatim, Paul-owned, docs/rubric-v1.md) beside true-check, with audit changes 2-5: principle names map to true-check PRINCIPLE_NAMES, the never-gated check reads true-check's NEVER_GATED (keyword backstop kept), the card rule text is cut to 60 chars (full rule in the candidate), and a 20 s budget with one retry inside it. Gemini gemini-4-neon-low through agy only; no Cursor or other fallback; any failure is an honest 'unavailable', exit 0. Never writes the scorecard. --- .github/workflows/ci.yml | 3 + bin/poteto-judge | 297 +++++++++++++++++++++++++++++++++++++ docs/rubric-v1.md | 48 ++++++ tests/test_poteto_judge.py | 248 +++++++++++++++++++++++++++++++ 4 files changed, 596 insertions(+) create mode 100755 bin/poteto-judge create mode 100644 docs/rubric-v1.md create mode 100644 tests/test_poteto_judge.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4cfeee..ff65b62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,6 +137,9 @@ jobs: - name: Run the HITL scorecard lint tests run: python3 -W error::ResourceWarning tests/test_lint_scorecard.py -v + - name: Run the poteto-judge tests + run: python3 -W error::ResourceWarning tests/test_poteto_judge.py -v + - name: Run the outcome ledger tests run: python3 tests/test_guild_ledger.py -v diff --git a/bin/poteto-judge b/bin/poteto-judge new file mode 100755 index 0000000..adfb44a --- /dev/null +++ b/bin/poteto-judge @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""poteto-judge: one other-family judge call per decision card. Never blocks a card. + +usage: poteto-judge card DECISION_ID + poteto-judge request DECISION_ID [--true-subject SUBJECT.json] + +card prints one JSON object {"line", "text", "row", "candidate"}: + line "🥔 Poteto: · ", "🥔 Poteto: no lean ()" or + "🥔 Poteto: unavailable ()". A lean is shown only when the judge + named an option letter and one rubric principle exactly; anything else is + unavailable, never a guessed lean. + text "🤖 Automate: rule () · " | "assist · " | + "keep human · " | "unavailable ()". + row a stage "poteto-shadow" scorecard row (bot, decision_id, poteto_*, auto_*). + poteto-judge never writes it: the caller (decision-options) appends it + through scorecard-append. + candidate for a valid "rule" answer, {key, bot, kind, rule (full text), decision_id, + why}; else null. key = sha256(bot|kind|normalized rule)[:12]. +It exits 0 on every model problem (error, timeout, bad JSON, unlisted principle); +exit 1 only when the log has no pre-card options for DECISION_ID, 2 on usage. + +request prints the request without calling a model. With --true-subject it is the +shared request: true-check's E and P questions (from bin/true-check itself) plus the +poteto question, so one call answers all four. true-check reads only answers.E and +answers.P; poteto-judge reads answers.poteto (or a flat answer). + +Blind packet: options, notes and gate_candidate (plus bot, for the row) from rows +logged before the first card-built or resolution row. Never bot_lean, jev_* or +anything written after the card. + +Rubric: Paul-owned docs/rubric-vN.md beside true-check (highest N), or +$POTETO_RUBRIC. Its "- Name: ..." lines are the principle list; each must map to a +true-check PRINCIPLE_NAMES slug. The version logged is vN-. + +Never-gated: a "rule" naming one of true-check's NEVER_GATED actions (or the +keyword backstop: send, post, pay, delete, close, booking, account, permission, +share, ...) is "unavailable (never-gated action)". It never creates a gate. + +Seat: Gemini gemini-4-neon-low through agy (another family from the bots and +from Jev, not Opus). No fallback seat: if agy fails, the lean is unavailable. +Never metered Cursor. Budget $POTETO_JUDGE_TIMEOUT seconds (default 20) for the +call and at most one retry inside it. + +Env: HITL_SCORECARD_LOG | SCORECARD_FILE (log), POTETO_RUBRIC, POTETO_JUDGE_TIMEOUT, +POTETO_JUDGE_CMD (tests: a command reading the prompt on stdin). +""" +from __future__ import annotations + +import glob +import hashlib +import importlib.machinery +import importlib.util +import json +import os +import re +import shutil +import subprocess +import sys +import time +from datetime import datetime + +HERE = os.path.dirname(os.path.realpath(__file__)) +ROOT = os.path.dirname(HERE) +TRUE_CHECK = os.path.join(HERE, "true-check") +DEFAULT_LOG = os.path.expanduser("~/agent-data/fleet/experiments/hitl-scorecard/log.jsonl") +DEFAULT_MODEL = "gemini-4-neon-low" +DEFAULT_TIMEOUT = 20.0 +MIN_RETRY_S = 2.0 +CARD_RULE_MAX = 60 +POST_CARD = {"card-built", "resolution", "resolved", "decided", "ryan", "auto-proceed"} +PACKET_KEYS = ("bot", "options", "notes", "gate_candidate") +RULE_KINDS = {"gate-row", "check", "policy"} +BACKSTOP = re.compile(r"\b(send|sends|email|e-mail|text|sms|dm|post|reply|buy|purchase|pay|payment|order|" + r"delete|remove|trash|close|book|booking|account|password|permission|share)\b", re.I) +# Rubric names whose slug is not the plain hyphenated name. +SLUG_ALIASES = {"Sequence Work into Verifiable Units": "principle-sequence-verifiable-units"} + + +def true_check(): + loader = importlib.machinery.SourceFileLoader("true_check", TRUE_CHECK) + spec = importlib.util.spec_from_loader("true_check", loader) + mod = importlib.util.module_from_spec(spec) + loader.exec_module(mod) + return mod + + +def never_gated_re(tc=None) -> re.Pattern: + tc = tc or true_check() + words = [re.escape(w).replace(r"\-", "[- ]") for w in tc.NEVER_GATED] + return re.compile(r"\b(" + "|".join(words) + r")", re.I) + + +def principle_slug(name: str) -> str: + return SLUG_ALIASES.get(name) or "principle-" + "-".join(name.lower().replace("-", " ").split()) + + +def rubric_path() -> str: + if os.environ.get("POTETO_RUBRIC"): + return os.environ["POTETO_RUBRIC"] + found = [] + for p in glob.glob(os.path.join(ROOT, "docs", "rubric-v*.md")): + m = re.fullmatch(r"rubric-v(\d+)\.md", os.path.basename(p)) + if m: + found.append((int(m.group(1)), p)) + if not found: + raise FileNotFoundError("no docs/rubric-vN.md beside true-check") + return max(found)[1] + + +def rubric(path: str | None = None): + path = path or rubric_path() + with open(path, encoding="utf-8") as f: + text = f.read() + names = set(re.findall(r"^- ([A-Z][A-Za-z -]+?):", text, re.M)) + m = re.search(r"rubric-(v\d+)\.md$", os.path.basename(path)) + version = (m.group(1) if m else "v?") + "-" + hashlib.sha256(text.encode()).hexdigest()[:8] + return text, names, version + + +def log_path() -> str: + return os.environ.get("HITL_SCORECARD_LOG") or os.environ.get("SCORECARD_FILE") or DEFAULT_LOG + + +def blind_packet(did: str, path: str | None = None) -> dict: + merged = {} + with open(path or log_path(), encoding="utf-8", errors="replace") as f: + for line in f: + try: + r = json.loads(line) + except ValueError: + continue + if not isinstance(r, dict) or r.get("decision_id") != did: + continue + if r.get("stage") in POST_CARD or "ryan_pick" in r: + break + for k in PACKET_KEYS: + if k in r: + merged[k] = r[k] + return merged + + +def prompt_for(packet: dict, text: str) -> str: + return text + "\n\nDecision packet:\n" + json.dumps(packet, ensure_ascii=False, indent=1) + + +def shared_request(packet: dict, subject: dict, path: str | None = None) -> dict: + """true-check's E/P request plus the poteto question: one call answers both.""" + tc = true_check() + text, _, version = rubric(path) + req = tc.judge_request(subject, tc.uses_nodiff(subject), None, None) + req["questions"]["poteto"] = {"type": "object", "rubric": version, "prompt": prompt_for(packet, text)} + return req + + +def answer_of(raw: dict) -> dict: + a = raw.get("answers") if isinstance(raw.get("answers"), dict) else None + if a is not None and isinstance(a.get("poteto"), dict): + return a["poteto"] + return raw + + +def default_cmd() -> str: + return f'agy --model {DEFAULT_MODEL} --disable-slash-commands -p "$(cat)"' + + +def ask_once(prompt: str, timeout: float) -> dict: + cmd = os.environ.get("POTETO_JUDGE_CMD") + if not cmd: + if not shutil.which("agy"): + raise RuntimeError("agy not on PATH") + cmd = default_cmd() + p = subprocess.run(cmd, shell=True, input=prompt, capture_output=True, text=True, timeout=timeout) + if p.returncode != 0: + err = re.search(r'"status":"([A-Z_]+)"', p.stdout + p.stderr) + raise RuntimeError(f"judge exit {p.returncode}" + (f" {err.group(1)}" if err else "")) + m = re.search(r"\{.*\}", p.stdout, re.S) + if not m: + raise RuntimeError("no JSON in judge answer") + raw = json.loads(m.group(0)) + if not isinstance(raw, dict): + raise RuntimeError("judge answer is not an object") + return answer_of(raw) + + +def ask(prompt: str, budget: float) -> dict: + """One call, plus one retry only if the budget has room. A timeout is not retried.""" + t0 = time.monotonic() + try: + return ask_once(prompt, budget) + except subprocess.TimeoutExpired: + raise + except Exception: + left = budget - (time.monotonic() - t0) + if left < MIN_RETRY_S: + raise + return ask_once(prompt, left) + + +def clip(s: str, n: int) -> str: + return s if len(s) <= n else s[: n - 1] + "…" + + +def automate(a: dict, packet: dict, did: str, gated: re.Pattern): + """Return (row fields, card text, candidate or None). Never raises.""" + state, kind, rule = a.get("automate"), a.get("rule_kind"), str(a.get("rule") or "").strip() + why = str(a.get("automate_why") or "").strip()[:80] + banned = bool(rule) and bool(gated.search(rule) or BACKSTOP.search(rule)) + if state == "rule" and kind in RULE_KINDS and rule and len(rule.split()) <= 30 and not banned: + norm = " ".join(rule.lower().split()) + key = hashlib.sha256(f"{packet.get('bot')}|{kind}|{norm}".encode()).hexdigest()[:12] + cand = {"key": key, "bot": packet.get("bot"), "kind": kind, "rule": rule, "decision_id": did, "why": why} + fields = {"auto_state": "rule", "auto_kind": kind, "auto_rule": rule, "auto_why": why} + return fields, f"🤖 Automate: rule ({kind}) · {clip(rule, CARD_RULE_MAX)}", cand + if state == "assist": + return {"auto_state": "assist", "auto_why": why}, f"🤖 Automate: assist · {why}", None + if state == "human": + return {"auto_state": "human", "auto_why": why}, f"🤖 Automate: keep human · {why}", None + reason = "never-gated action" if state == "rule" and banned else "invalid automate answer" + return {"auto_state": "unavailable", "auto_reason": reason}, f"🤖 Automate: unavailable ({reason})", None + + +def judge_card(did: str) -> dict | None: + text, names, version = rubric() + tc = true_check() + names = {n for n in names if principle_slug(n) in tc.PRINCIPLE_NAMES} + gated = never_gated_re(tc) + packet = blind_packet(did) + if not isinstance(packet.get("options"), dict) or not packet["options"]: + return None + custom = bool(os.environ.get("POTETO_JUDGE_CMD")) + row = {"ts": datetime.now().astimezone().isoformat(timespec="seconds"), "bot": packet.get("bot"), + "decision_id": did, "stage": "poteto-shadow", "poteto_rubric": version, + "poteto_model": "custom" if custom else DEFAULT_MODEL} + text_line, cand = "🤖 Automate: unavailable (no answer)", None + t0 = time.monotonic() + try: + a = ask(prompt_for(packet, text), float(os.environ.get("POTETO_JUDGE_TIMEOUT") or DEFAULT_TIMEOUT)) + af, text_line, cand = automate(a, packet, did, gated) + row.update(af) + lean, principle = a.get("lean"), a.get("principle") + if lean is None: + row.update(poteto_lean=None, poteto_why=str(a.get("why") or "")[:120]) + line = f"🥔 Poteto: no lean ({row['poteto_why']})" + elif lean not in packet["options"]: + raise ValueError(f"letter {lean!r} not in options") + elif principle not in names: + raise ValueError(f"principle {principle!r} not in rubric") + else: + conf = a.get("conf") + row.update(poteto_lean=lean, poteto_principle=principle, poteto_why=str(a.get("why") or "")[:120], + poteto_conf=conf if isinstance(conf, (int, float)) and not isinstance(conf, bool) else None) + line = f"🥔 Poteto: {lean} · {principle}" + except subprocess.TimeoutExpired: + row.update(poteto_lean="unavailable", poteto_reason="timeout", auto_state="unavailable", + auto_reason="timeout") + line, text_line, cand = "🥔 Poteto: unavailable (timeout)", "🤖 Automate: unavailable (timeout)", None + except Exception as e: # never block a card + reason = (str(e) or type(e).__name__)[:80] + row.update(poteto_lean="unavailable", poteto_reason=reason) + if "auto_state" not in row: + row.update(auto_state="unavailable", auto_reason=reason) + line = f"🥔 Poteto: unavailable ({reason})" + row["poteto_latency_s"] = round(time.monotonic() - t0, 1) + return {"line": line, "text": text_line, "row": row, "candidate": cand} + + +def main(argv: list[str]) -> int: + if len(argv) == 2 and argv[0] == "card": + try: + out = judge_card(argv[1]) + except FileNotFoundError as e: + print(f"poteto-judge: {e}", file=sys.stderr) + return 1 + if out is None: + print(f"poteto-judge: no pre-card options for {argv[1]}", file=sys.stderr) + return 1 + print(json.dumps(out, ensure_ascii=False)) + return 0 + if len(argv) in (2, 4) and argv[0] == "request": + packet = blind_packet(argv[1]) + if len(argv) == 4 and argv[2] == "--true-subject": + with open(argv[3]) as f: + req = shared_request(packet, json.load(f)) + elif len(argv) == 2: + text, _, version = rubric() + req = {"rubric": version, "prompt": prompt_for(packet, text)} + else: + print(__doc__, file=sys.stderr) + return 2 + print(json.dumps(req, ensure_ascii=False, indent=1)) + return 0 + print(__doc__, file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/docs/rubric-v1.md b/docs/rubric-v1.md new file mode 100644 index 0000000..1edc7f5 --- /dev/null +++ b/docs/rubric-v1.md @@ -0,0 +1,48 @@ +# Poteto judge rubric v1 (owner: Practice Paul; 2026-11-24; shadow only; adds the automate question) + +You judge which option of a decision best follows pstack, Lauren Tan's (@poteto) +engineering and practice principles. You are not judging what Ryan will like. +You get the options and the context a bot wrote before the card was built. You +do not see any bot's or Jev's lean. + +Pick exactly one option letter, or null when no principle below clearly favors +one option. Name the ONE principle that most drives the pick, spelled exactly as +in this list. A pick without a listed principle is invalid. + +Principles (apply-when, from pstack poteto-mode): +- Laziness Protocol: smallest change that solves it; bias to deletion. +- Subtract Before You Add: remove complexity first; design for observed usage. +- Build the Lever: build the tool/script that does or proves it, not by hand. +- Encode Lessons in Structure: a check, flag or script beats another instruction. +- Experience First: user (Ryan) delight over implementation convenience. +- Never Block on the Human: reversible work proceeds; present the result. +- Prove It Works: verify against the real artifact before calling it done. +- Fix Root Causes: fix where it first went wrong; a guard is not a fix. +- Explain the Number: do not trust or act on an unexplained measurement. +- Minimize Reader Load: fewer layers and less hidden state. +- Model the Domain: encode the domain in one structure, not scattered rules. +- Make Operations Idempotent: rerunnable, converges to one end state. +- Outcome-Oriented Execution: converge on the target; no throwaway states. +- Redesign from First Principles: redesign as if the requirement was day one. +- Attack the Premise: repeated failures on one premise; test the premise. +- Separate Before Serializing Shared State: remove sharing before locking. +- Sequence Work into Verifiable Units: small steps that each end in a check. + +Hard rules: sends, purchases, deletions and account changes stay with Ryan; +never lean toward an option that does one of those silently. If the options are +about taste or money with no engineering or practice angle, answer null. + +Second question, about the decision itself (not an option): next time a +decision like this comes up, how deterministic can it be? Prefer the most +deterministic answer that is safe (Encode Lessons in Structure, Build the Lever): +- "rule": a fixed rule could decide it without judgment. Say which kind: + "gate-row" (an autonomy-gate ledger row), "check" (a script or lint), or + "policy" (a standing written rule with no judgment left). Write the rule in + 25 words or fewer, specific enough to build. Sends, purchases, deletions, + account changes and bookings can never be "rule". +- "assist": judgment stays, but a script or model can prepare most of it. +- "human": Ryan's own call (taste, relationships, money, one-off context). + +Reply with ONLY one JSON object, no prose: +{"lean": "A"|"B"|...|null, "principle": ""|null, "why": "<= 15 words", "conf": 0.0-1.0, + "automate": "rule"|"assist"|"human", "rule_kind": "gate-row"|"check"|"policy"|null, "rule": "<= 25 words"|null, "automate_why": "<= 12 words"} diff --git a/tests/test_poteto_judge.py b/tests/test_poteto_judge.py new file mode 100644 index 0000000..b5d7bec --- /dev/null +++ b/tests/test_poteto_judge.py @@ -0,0 +1,248 @@ +"""Behavior tests for bin/poteto-judge (Paul's 13 prototype tests, ported, plus the shared-call, +never-gated, no-Cursor-fallback, timeout-budget and card-truncation tests). + +Run: python3 tests/test_poteto_judge.py -v +""" +import importlib.machinery +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +TOOL = os.path.join(ROOT, "bin", "poteto-judge") +TRUE_CHECK = os.path.join(ROOT, "bin", "true-check") +RUBRIC = os.path.join(ROOT, "docs", "rubric-v1.md") + +ROWS = [ + {"ts": "2026-11-20T12:45:03-08:00", "bot": "Ledger Leo", "decision_id": "d1", "stage": "pending", + "options": {"A": "Hide dupes now", "B": "Hold cleanup", "C": "Ask first"}, + "bot_lean": "A", "notes": "restore validation"}, + {"ts": "2026-11-20T12:45:04-08:00", "decision_id": "d1", "stage": "jev", "jev_lean": "B"}, + {"ts": "2026-11-20T12:46:00-08:00", "decision_id": "d1", "stage": "card-built", "card_id": "abc"}, + {"ts": "2026-11-20T13:07:00-08:00", "decision_id": "d1", "stage": "resolution", "ryan_pick": "A", + "notes": "RYAN SAID A"}, +] + + +def load(path, name): + loader = importlib.machinery.SourceFileLoader(name, path) + spec = importlib.util.spec_from_loader(name, loader) + mod = importlib.util.module_from_spec(spec) + loader.exec_module(mod) + return mod + + +def stub(d, out, rc=0, sleep=0, name="stub.sh", count=None): + seen = os.path.join(d, "prompt.txt") + path = os.path.join(d, name) + tally = f"echo x >> {count}\n" if count else "" + with open(path, "w") as f: + f.write(f"#!/bin/sh\n{tally}cat > {seen}\nsleep {sleep}\nprintf '%s' '{out}'\nexit {rc}\n") + os.chmod(path, 0o755) + return path, seen + + +def run(stub_out, stub_rc=0, sleep=0, timeout="5", did="d1", extra_env=None): + d = tempfile.mkdtemp() + log = os.path.join(d, "log.jsonl") + with open(log, "w") as f: + for r in ROWS: + f.write(json.dumps(r) + "\n") + cmd, seen = stub(d, stub_out, stub_rc, sleep) + env = dict(os.environ, POTETO_RUBRIC=RUBRIC, HITL_SCORECARD_LOG=log, + POTETO_JUDGE_CMD=cmd, POTETO_JUDGE_TIMEOUT=timeout) + env.pop("SCORECARD_FILE", None) + env.update(extra_env or {}) + p = subprocess.run([sys.executable, TOOL, "card", did], capture_output=True, text=True, env=env) + prompt = "" + if os.path.exists(seen): + with open(seen) as f: + prompt = f.read() + with open(log) as f: + after = f.read() + return p, prompt, after, log + + +GOOD = '{"lean": "B", "principle": "Subtract Before You Add", "why": "hold the risky half", "conf": 0.7}' + + +class T(unittest.TestCase): + def test_good_answer_prints_one_card_line_naming_principle(self): + p, _, _, _ = run(GOOD) + self.assertEqual(p.returncode, 0, p.stderr) + out = json.loads(p.stdout) + self.assertEqual(out["line"], "🥔 Poteto: B · Subtract Before You Add") + self.assertEqual(out["row"]["poteto_lean"], "B") + self.assertEqual(out["row"]["poteto_principle"], "Subtract Before You Add") + self.assertIn("poteto_rubric", out["row"]) + + def test_unlisted_principle_is_unavailable_not_a_lean(self): + p, _, _, _ = run('{"lean": "B", "principle": "Vibes", "why": "x", "conf": 0.9}') + self.assertEqual(p.returncode, 0) + out = json.loads(p.stdout) + self.assertTrue(out["line"].startswith("🥔 Poteto: unavailable"), out) + self.assertEqual(out["row"]["poteto_lean"], "unavailable") + + def test_letter_not_in_options_is_unavailable(self): + p, _, _, _ = run('{"lean": "Z", "principle": "Build the Lever", "why": "x", "conf": 0.9}') + self.assertEqual(json.loads(p.stdout)["row"]["poteto_lean"], "unavailable") + + def test_model_error_never_blocks(self): + p, _, _, _ = run("boom", stub_rc=1) + self.assertEqual(p.returncode, 0) + self.assertTrue(json.loads(p.stdout)["line"].startswith("🥔 Poteto: unavailable")) + + def test_timeout_never_blocks(self): + p, _, _, _ = run(GOOD, sleep=3, timeout="1") + self.assertEqual(p.returncode, 0) + self.assertIn("timeout", json.loads(p.stdout)["row"]["poteto_reason"]) + + def test_null_lean_is_shown_as_no_lean(self): + p, _, _, _ = run('{"lean": null, "principle": null, "why": "taste call", "conf": 0.2}') + self.assertEqual(json.loads(p.stdout)["line"], "🥔 Poteto: no lean (taste call)") + + def test_blind_packet_has_no_leans_and_no_post_card_rows(self): + _, prompt, _, _ = run(GOOD) + self.assertIn("Hide dupes now", prompt) + self.assertNotIn("RYAN SAID A", prompt) + self.assertNotIn("bot_lean", prompt) + self.assertNotIn("jev_lean", prompt) + + def test_never_writes_the_scorecard(self): + _, _, after, _ = run(GOOD) + self.assertEqual(after.count("\n"), len(ROWS)) + + +RULE = ('{"lean": "A", "principle": "Build the Lever", "why": "x", "conf": 0.8, "automate": "rule", ' + '"rule_kind": "check", "rule": "Hide restored rows that pair 1:1 by date and amount after a CSV backup", ' + '"automate_why": "same pattern each restore"}') +RULE_TEXT = "Hide restored rows that pair 1:1 by date and amount after a CSV backup" + + +class Automate(unittest.TestCase): + def test_rule_answer_gives_one_text_line_and_a_candidate(self): + p, _, _, _ = run(RULE) + out = json.loads(p.stdout) + # Paul audit change 4: the card line carries at most 60 characters of the rule. + self.assertEqual(out["text"], "🤖 Automate: rule (check) · " + RULE_TEXT[:59] + "…") + self.assertEqual(out["row"]["auto_state"], "rule") + c = out["candidate"] + self.assertEqual((c["kind"], c["bot"], c["decision_id"]), ("check", "Ledger Leo", "d1")) + self.assertEqual(len(c["key"]), 12) + self.assertEqual(c["rule"], RULE_TEXT) # the full rule goes to rule-candidates + + def test_rule_without_rule_text_is_unavailable_and_no_candidate(self): + p, _, _, _ = run('{"lean": "A", "principle": "Build the Lever", "why": "x", "automate": "rule", ' + '"rule_kind": null, "rule": null}') + out = json.loads(p.stdout) + self.assertEqual(out["row"]["auto_state"], "unavailable") + self.assertIsNone(out["candidate"]) + self.assertEqual(out["line"], "🥔 Poteto: A · Build the Lever") + + def test_human_and_assist_lines(self): + p, _, _, _ = run('{"lean": null, "principle": null, "why": "taste", "automate": "human", ' + '"automate_why": "taste call"}') + self.assertEqual(json.loads(p.stdout)["text"], "🤖 Automate: keep human · taste call") + p, _, _, _ = run('{"lean": null, "principle": null, "why": "t", "automate": "assist", ' + '"automate_why": "script drafts it"}') + self.assertEqual(json.loads(p.stdout)["text"], "🤖 Automate: assist · script drafts it") + + def test_never_gated_action_cannot_be_rule(self): + p, _, _, _ = run('{"lean": "A", "principle": "Build the Lever", "why": "x", "automate": "rule", ' + '"rule_kind": "gate-row", "rule": "Auto-send the nudge email to Tim"}') + self.assertEqual(json.loads(p.stdout)["row"]["auto_state"], "unavailable") + + +class Rubric(unittest.TestCase): + def test_every_rubric_principle_is_accepted(self): + _, names, _ = load(TOOL, "poteto_judge_r").rubric(RUBRIC) + for n in ("Outcome-Oriented Execution", "Separate Before Serializing Shared State", "Build the Lever"): + self.assertIn(n, names) + self.assertEqual(len(names), 17) + + +class Shared(unittest.TestCase): + """One judge, shared with true-check (design 2, audit changes 2 and 3).""" + + def test_rubric_principles_are_true_check_principles(self): + pj, tc = load(TOOL, "poteto_judge_s1"), load(TRUE_CHECK, "true_check_s1") + _, names, _ = pj.rubric(RUBRIC) + for n in names: + self.assertIn(pj.principle_slug(n), tc.PRINCIPLE_NAMES, n) + + def test_never_gated_list_is_read_from_true_check(self): + # "phishing" is only in true-check's NEVER_GATED, not in the keyword backstop. + p, _, _, _ = run('{"lean": "A", "principle": "Build the Lever", "why": "x", "automate": "rule", ' + '"rule_kind": "policy", "rule": "Mark phishing lookalikes as read"}') + row = json.loads(p.stdout)["row"] + self.assertEqual((row["auto_state"], row["auto_reason"]), ("unavailable", "never-gated action")) + + def test_shared_call_true_check_reads_only_e_and_p(self): + """One request carries true-check's E/P questions and the poteto question. The same + answer gives true-check its letters (poteto keys ignored) and poteto-judge its lean.""" + pj, tc = load(TOOL, "poteto_judge_s2"), load(TRUE_CHECK, "true_check_s2") + subject = {"action": "local-build", "goal": "make the card lean deterministic", + "diff": {"patch": "diff --git a/x.py b/x.py\n"}, "evidence": ["tests/test_x.py"]} + packet = {"bot": "Ledger Leo", "options": {"A": "go", "B": "hold"}} + req = pj.shared_request(packet, subject, RUBRIC) + self.assertEqual(set(req["questions"]), {"E", "P", "poteto"}) + self.assertEqual(req["questions"]["E"], tc.judge_request(subject, False, None, None)["questions"]["E"]) + self.assertEqual(req["principles"], list(tc.PRINCIPLE_NAMES)) + ep = {"E": {"choice": "pass", "confidence": 0.9, "cites": "tests/test_x.py"}, + "P": {"choice": "pass", "confidence": 0.9}} + combined = {"id": "c1", "answers": dict(ep, poteto={ + "lean": "A", "principle": "Prove It Works", "why": "w", "conf": 0.8, + "automate": "assist", "automate_why": "script preps it"})} + self.assertEqual(tc.judge_letters(combined, "", subject), + tc.judge_letters({"id": "c1", "answers": ep}, "", subject)) + a = pj.answer_of(combined) + self.assertEqual((a["lean"], a["principle"]), ("A", "Prove It Works")) + + +class Seat(unittest.TestCase): + def test_default_seat_is_gemini_neon_low_through_agy(self): + pj = load(TOOL, "poteto_judge_seat") + self.assertEqual(pj.DEFAULT_MODEL, "gemini-4-neon-low") + self.assertTrue(pj.default_cmd().startswith("agy --model gemini-4-neon-low ")) + self.assertEqual(pj.DEFAULT_TIMEOUT, 20.0) + + def test_no_agy_is_unavailable_and_never_falls_back_to_cursor(self): + d = tempfile.mkdtemp() + calls = os.path.join(d, "cursor-calls") + for name in ("cursor-agent", "cursor", "agent", "judge-ask"): + stub(d, GOOD, name=name, count=calls) + log = os.path.join(d, "log.jsonl") + with open(log, "w") as f: + for r in ROWS: + f.write(json.dumps(r) + "\n") + env = {"PATH": d + ":/usr/bin:/bin", "HITL_SCORECARD_LOG": log, "POTETO_RUBRIC": RUBRIC} + p = subprocess.run([sys.executable, TOOL, "card", "d1"], capture_output=True, text=True, env=env) + self.assertEqual(p.returncode, 0, p.stderr) + out = json.loads(p.stdout) + self.assertEqual(out["row"]["poteto_lean"], "unavailable") + self.assertFalse(os.path.exists(calls), "a Cursor or other seat was called") + + def test_one_retry_inside_the_budget_then_unavailable(self): + d = tempfile.mkdtemp() + calls = os.path.join(d, "calls") + cmd, _ = stub(d, "boom", rc=1, count=calls) + p, _, _, _ = run("unused", extra_env={"POTETO_JUDGE_CMD": cmd}) + self.assertEqual(json.loads(p.stdout)["row"]["poteto_lean"], "unavailable") + with open(calls) as f: + self.assertEqual(len(f.read().split()), 2) + + def test_row_carries_bot_and_model_for_the_scorecard(self): + p, _, _, _ = run(GOOD) + row = json.loads(p.stdout)["row"] + self.assertEqual((row["bot"], row["stage"], row["decision_id"]), ("Ledger Leo", "poteto-shadow", "d1")) + self.assertIn("poteto_model", row) + self.assertIsInstance(row["poteto_latency_s"], float) + + +if __name__ == "__main__": + unittest.main() From cbadc42cd9cf96c679d347aa9eb412db6f9bb92b Mon Sep 17 00:00:00 2001 From: Ryan Weiss <1996129+rymiwe@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:17:32 -0800 Subject: [PATCH 2/3] lint-scorecard: accept stage poteto-shadow rows; scorecard-append fills match_poteto POTETO row code: poteto_rubric set; poteto_lean a letter (with principle), null or unavailable (with reason); auto_state in rule/assist/human/unavailable, rule needs auto_kind and auto_rule; match_poteto must be a bool. A resolution row without match_poteto gets it from the latest poteto-shadow lean, under the append lock. Live log copy: 809 findings before and after (no new code hits). --- bin/lint-scorecard | 42 +++++++++++++- bin/scorecard-append | 37 ++++++++++++- tests/test_lint_scorecard.py | 103 +++++++++++++++++++++++++++++++++++ 3 files changed, 179 insertions(+), 3 deletions(-) diff --git a/bin/lint-scorecard b/bin/lint-scorecard index 9a3c921..d107e22 100755 --- a/bin/lint-scorecard +++ b/bin/lint-scorecard @@ -26,7 +26,12 @@ The baseline counts non-empty rows, the same rows the lint counts. Rules come from skill jev-hitl-triage (Steps 2-4 and the Scorecard section). Exit 2 on usage error or missing file. -Row codes: JSON, TS, BOT, DECISION_ID, AUTOMATABLE, JEV_REASON +Row codes: JSON, TS, BOT, DECISION_ID, AUTOMATABLE, JEV_REASON, POTETO +POTETO (stage poteto-shadow rows, from poteto-judge): poteto_rubric is set; +poteto_lean is one option letter (with poteto_principle), null (no lean) or +"unavailable" (with poteto_reason); auto_state is rule, assist, human or +unavailable, and rule needs auto_kind gate-row, check or policy plus auto_rule. +On any row, auto_state (if present) uses that set and match_poteto is a bool. Decision codes (a decision is any decision_id with an `options` or `bot_lean` row): NO_BOT_LEAN, NO_BOT_LEAN_TS, NO_JEV_LEAN, NO_JEV_TS, LEAN_ORDER (bot_lean_ts later than jev_ts). @@ -44,6 +49,9 @@ from collections import Counter DEFAULT_FILE = os.path.expanduser("~/agent-data/fleet/experiments/hitl-scorecard/log.jsonl") GROUP_PLACEHOLDERS = frozenset({"Family", "Household", "Money", "Media", "Staff"}) AUTOMATABLE = frozenset({"full", "partial", "no"}) +AUTO_STATES = frozenset({"rule", "assist", "human", "unavailable"}) +RULE_KINDS = frozenset({"gate-row", "check", "policy"}) +LETTER_RE = re.compile(r"^[A-Z]$") TS_RE = re.compile( r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:[+-]\d{2}:?\d{2}|Z)$" ) @@ -140,6 +148,38 @@ def row_problems(row, names: set[str]) -> list[tuple[str, str]]: out.append(("AUTOMATABLE", f"{k}={row[k]!r} must be full, partial or no")) if row.get("jev_lean") == "unavailable" and not row.get("jev_reason"): out.append(("JEV_REASON", "jev_lean=unavailable needs jev_reason in the same row")) + out.extend(("POTETO", why) for why in poteto_problems(row)) + return out + + +def poteto_problems(row: dict) -> list[str]: + out = [] + if "match_poteto" in row and not isinstance(row["match_poteto"], bool): + out.append(f"match_poteto={row['match_poteto']!r} must be true or false") + if "auto_state" in row and row["auto_state"] not in AUTO_STATES: + out.append(f"auto_state={row['auto_state']!r} must be rule, assist, human or unavailable") + if row.get("stage") != "poteto-shadow": + return out + if not isinstance(row.get("poteto_rubric"), str) or not row["poteto_rubric"].strip(): + out.append("poteto-shadow row needs poteto_rubric") + if "poteto_lean" not in row: + out.append("poteto-shadow row needs poteto_lean (a letter, null or unavailable)") + lean = row.get("poteto_lean") + if lean == "unavailable": + if not row.get("poteto_reason"): + out.append("poteto_lean=unavailable needs poteto_reason") + elif lean is not None: + if not isinstance(lean, str) or not LETTER_RE.match(lean): + out.append(f"poteto_lean={lean!r} must be one option letter, null or unavailable") + elif not isinstance(row.get("poteto_principle"), str) or not row["poteto_principle"].strip(): + out.append("a poteto_lean letter needs poteto_principle") + if "auto_state" not in row: + out.append("poteto-shadow row needs auto_state") + elif row["auto_state"] == "rule": + if row.get("auto_kind") not in RULE_KINDS: + out.append(f"auto_kind={row.get('auto_kind')!r} must be gate-row, check or policy") + if not isinstance(row.get("auto_rule"), str) or not row["auto_rule"].strip(): + out.append("auto_state=rule needs auto_rule") return out diff --git a/bin/scorecard-append b/bin/scorecard-append index 78d8a37..c389c39 100755 --- a/bin/scorecard-append +++ b/bin/scorecard-append @@ -11,6 +11,12 @@ flock on LOG.lock. LOG is --file, else $SCORECARD_FILE or its alias $HITL_SCORECARD_LOG, else the fleet default; both env vars set to different files exits 2 with the log untouched (same rule as lint-scorecard). Never rewrites old rows. No secrets in rows. + +match_poteto: a resolution row (one with ryan_pick) that has no match_poteto +gets it filled under the lock: true when ryan_pick's letter equals the latest +stage poteto-shadow row's poteto_lean letter for that decision_id, false when +it differs. No poteto-shadow row, or a lean that is null or unavailable, +leaves the row as written. A match_poteto the writer set is kept. """ import fcntl import json @@ -52,13 +58,40 @@ def main(argv) -> int: sys.stderr.write("scorecard-append: refused; log unchanged\n") return 1 row = json.loads(text.strip()) - line = json.dumps(row, ensure_ascii=False) + "\n" with open(path + ".lock", "a") as lk: fcntl.flock(lk, fcntl.LOCK_EX) + fill_match_poteto(path, row) with open(path, "a", encoding="utf-8") as f: - f.write(line) + f.write(json.dumps(row, ensure_ascii=False) + "\n") return 0 +def poteto_lean_of(path, did): + lean = None + try: + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + if '"poteto-shadow"' not in line: + continue + try: + r = json.loads(line) + except ValueError: + continue + if isinstance(r, dict) and r.get("decision_id") == did and r.get("stage") == "poteto-shadow": + lean = r.get("poteto_lean") + except FileNotFoundError: + return None + return lean if isinstance(lean, str) and len(lean) == 1 and lean.isupper() else None + + +def fill_match_poteto(path, row): + pick = row.get("ryan_pick") + if "match_poteto" in row or not isinstance(pick, str) or not pick.strip(): + return + lean = poteto_lean_of(path, row.get("decision_id")) + if lean is not None: + row["match_poteto"] = pick.strip()[:1] == lean + + if __name__ == "__main__": sys.exit(main(sys.argv[1:])) diff --git a/tests/test_lint_scorecard.py b/tests/test_lint_scorecard.py index 473721f..7177a9a 100644 --- a/tests/test_lint_scorecard.py +++ b/tests/test_lint_scorecard.py @@ -385,5 +385,108 @@ def test_jev_raw_is_not_a_jev_lean(self): self.assertIn("NO_JEV_LEAN", r.stdout) + +def poteto_row(did="cole-x-2026-11-24", **kv): + row = {"ts": TS2, "bot": "Code Cole", "decision_id": did, "stage": "poteto-shadow", + "poteto_rubric": "v1-b3b273cf", "poteto_model": "gemini-4-neon-low", + "poteto_lean": "A", "poteto_principle": "Build the Lever", "poteto_why": "w", + "poteto_conf": 0.8, "poteto_latency_s": 12.0, + "auto_state": "rule", "auto_kind": "check", "auto_rule": "lint it", "auto_why": "same each time"} + row.update(kv) + return {k: v for k, v in row.items() if v is not DROP} + + +DROP = object() + + +class PotetoShadowTests(Base): + """Stage poteto-shadow rows and match_poteto (poteto lean design 8; audit change 7).""" + + def lint_rows(self, *extra): + self.write(good_decision() + list(extra)) + return self.lint("--fail-any") + + def test_valid_poteto_rows_pass(self): + unavailable = poteto_row(poteto_lean="unavailable", poteto_reason="timeout", + poteto_principle=DROP, poteto_why=DROP, poteto_conf=DROP, + auto_state="unavailable", auto_reason="timeout", + auto_kind=DROP, auto_rule=DROP, auto_why=DROP) + no_lean = poteto_row(poteto_lean=None, poteto_principle=DROP, auto_state="human", + auto_kind=DROP, auto_rule=DROP) + r = self.lint_rows(poteto_row(), unavailable, no_lean) + self.assertEqual(r.returncode, 0, r.stdout) + + def test_old_automatable_vocabulary_is_not_an_auto_state(self): + r = self.lint_rows(poteto_row(auto_state="partial")) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("POTETO", r.stdout) + + def test_unavailable_lean_needs_a_reason(self): + r = self.lint_rows(poteto_row(poteto_lean="unavailable", poteto_principle=DROP)) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("POTETO", r.stdout) + + def test_letter_lean_needs_a_principle_and_rubric(self): + r = self.lint_rows(poteto_row(poteto_principle=DROP)) + self.assertEqual(r.returncode, 1, r.stdout) + r = self.lint_rows(poteto_row(poteto_rubric=DROP)) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("POTETO", r.stdout) + + def test_rule_state_needs_kind_and_rule(self): + r = self.lint_rows(poteto_row(auto_kind="vibes")) + self.assertEqual(r.returncode, 1, r.stdout) + r = self.lint_rows(poteto_row(auto_rule=DROP)) + self.assertEqual(r.returncode, 1, r.stdout) + + def test_match_poteto_must_be_bool(self): + did = good_decision()[0]["decision_id"] + res = {"ts": TS2, "bot": "Code Cole", "decision_id": did, "stage": "resolution", + "ryan_pick": "A", "match_bot": True, "match_jev": True, "match_poteto": "yes"} + r = self.lint_rows(res) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("POTETO", r.stdout) + + def test_append_refuses_a_bad_poteto_row(self): + self.write(good_decision()) + before = self.read_bytes() + r = self.append(json.dumps(poteto_row(auto_state="full"))) + self.assertEqual(r.returncode, 1, r.stderr) + self.assertEqual(self.read_bytes(), before) + + def resolution(self, pick, **kv): + did = good_decision()[0]["decision_id"] + row = {"ts": TS2, "bot": "Code Cole", "decision_id": did, "stage": "resolution", + "ryan_pick": pick, "match_bot": pick == "A", "match_jev": pick == "A"} + row.update(kv) + return json.dumps(row) + + def last_row(self): + return json.loads(self.read_text().splitlines()[-1]) + + def test_append_fills_match_poteto_on_a_resolution(self): + self.write(good_decision() + [poteto_row()]) + r = self.append(self.resolution("A")) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIs(self.last_row()["match_poteto"], True) + r = self.append(self.resolution("B: hold")) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIs(self.last_row()["match_poteto"], False) + + def test_append_leaves_match_poteto_off_without_a_poteto_lean(self): + unavailable = poteto_row(poteto_lean="unavailable", poteto_reason="timeout", poteto_principle=DROP, + auto_state="unavailable", auto_reason="timeout", auto_kind=DROP, auto_rule=DROP) + for rows in (good_decision(), good_decision() + [unavailable]): + self.write(rows) + r = self.append(self.resolution("A")) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertNotIn("match_poteto", self.last_row()) + + def test_append_keeps_a_written_match_poteto(self): + self.write(good_decision() + [poteto_row()]) + r = self.append(self.resolution("A", match_poteto=False)) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIs(self.last_row()["match_poteto"], False) + if __name__ == "__main__": unittest.main() From e6b63452b9c9bf8527e104734c24a4cf52ee437b Mon Sep 17 00:00:00 2001 From: Ryan Weiss <1996129+rymiwe@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:34:40 -0800 Subject: [PATCH 3/3] poteto-judge: retry transient errors only; never retry a quota 429 (Paul guild#96 R1) A quota error (429 / RESOURCE_EXHAUSTED) cannot succeed on retry, so it makes exactly one agy call. Only 5xx, UNAVAILABLE, DEADLINE_EXCEEDED and connection errors get the one retry inside the 20 s budget; timeouts, bad JSON, auth and unknown failures are not retried. Fail-first: 21 tests, failures=1 (429 made 2 calls), then 22 tests, failures=2 (401 and bad JSON retried); now 22 OK. --- bin/poteto-judge | 37 ++++++++++++++++++++++++++++++------- tests/test_poteto_judge.py | 29 ++++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/bin/poteto-judge b/bin/poteto-judge index adfb44a..7b76554 100755 --- a/bin/poteto-judge +++ b/bin/poteto-judge @@ -39,7 +39,10 @@ share, ...) is "unavailable (never-gated action)". It never creates a gate. Seat: Gemini gemini-4-neon-low through agy (another family from the bots and from Jev, not Opus). No fallback seat: if agy fails, the lean is unavailable. Never metered Cursor. Budget $POTETO_JUDGE_TIMEOUT seconds (default 20) for the -call and at most one retry inside it. +call and at most one retry inside it, for transient errors only (5xx, +UNAVAILABLE, DEADLINE_EXCEEDED, connection). A quota error (429 / +RESOURCE_EXHAUSTED), a timeout, bad JSON, auth or an unknown failure is never +retried. Env: HITL_SCORECARD_LOG | SCORECARD_FILE (log), POTETO_RUBRIC, POTETO_JUDGE_TIMEOUT, POTETO_JUDGE_CMD (tests: a command reading the prompt on stdin). @@ -159,6 +162,21 @@ def answer_of(raw: dict) -> dict: return raw +class TransientError(RuntimeError): + """A failure a second call can fix (5xx, UNAVAILABLE, DEADLINE_EXCEEDED, connection).""" + + +TRANSIENT = re.compile(r"\b(UNAVAILABLE|DEADLINE_EXCEEDED|INTERNAL|code 5\d\d|\"error_code\":\s*5\d\d|" + r"connection (reset|refused|closed)|ECONNRESET|temporarily unavailable)\b", re.I) + + +class QuotaError(RuntimeError): + """The seat's quota is out (429 / RESOURCE_EXHAUSTED): a retry cannot succeed.""" + + +QUOTA = re.compile(r"RESOURCE_EXHAUSTED|\bcode 429\b|\"error_code\":\s*429\b|quota reached", re.I) + + def default_cmd() -> str: return f'agy --model {DEFAULT_MODEL} --disable-slash-commands -p "$(cat)"' @@ -171,8 +189,14 @@ def ask_once(prompt: str, timeout: float) -> dict: cmd = default_cmd() p = subprocess.run(cmd, shell=True, input=prompt, capture_output=True, text=True, timeout=timeout) if p.returncode != 0: - err = re.search(r'"status":"([A-Z_]+)"', p.stdout + p.stderr) - raise RuntimeError(f"judge exit {p.returncode}" + (f" {err.group(1)}" if err else "")) + out = p.stdout + p.stderr + err = re.search(r'"status":"([A-Z_]+)"', out) + why = f"judge exit {p.returncode}" + (f" {err.group(1)}" if err else "") + if QUOTA.search(out): + raise QuotaError(why) + if TRANSIENT.search(out): + raise TransientError(why) + raise RuntimeError(why) m = re.search(r"\{.*\}", p.stdout, re.S) if not m: raise RuntimeError("no JSON in judge answer") @@ -183,13 +207,12 @@ def ask_once(prompt: str, timeout: float) -> dict: def ask(prompt: str, budget: float) -> dict: - """One call, plus one retry only if the budget has room. A timeout is not retried.""" + """One call, plus one retry for a transient error only, if the budget has room. + Quota (429), timeouts, bad JSON, auth and unknown failures are not retried.""" t0 = time.monotonic() try: return ask_once(prompt, budget) - except subprocess.TimeoutExpired: - raise - except Exception: + except TransientError: left = budget - (time.monotonic() - t0) if left < MIN_RETRY_S: raise diff --git a/tests/test_poteto_judge.py b/tests/test_poteto_judge.py index b5d7bec..1ac8077 100644 --- a/tests/test_poteto_judge.py +++ b/tests/test_poteto_judge.py @@ -230,12 +230,39 @@ def test_no_agy_is_unavailable_and_never_falls_back_to_cursor(self): def test_one_retry_inside_the_budget_then_unavailable(self): d = tempfile.mkdtemp() calls = os.path.join(d, "calls") - cmd, _ = stub(d, "boom", rc=1, count=calls) + cmd, _ = stub(d, "SERVICE_UNAVAILABLE (code 503)", rc=1, count=calls) p, _, _, _ = run("unused", extra_env={"POTETO_JUDGE_CMD": cmd}) self.assertEqual(json.loads(p.stdout)["row"]["poteto_lean"], "unavailable") with open(calls) as f: self.assertEqual(len(f.read().split()), 2) + def test_quota_429_is_not_retried(self): + """Paul guild#96 R1: a quota error cannot succeed on retry, so exactly 1 agy call.""" + d = tempfile.mkdtemp() + calls = os.path.join(d, "calls") + err = ('error: Individual quota reached. Resets in 2h40m49s.\\nAGY_ERROR: {"short_error":' + '"RESOURCE_EXHAUSTED (code 429): Individual quota reached.","status":"RESOURCE_EXHAUSTED",' + '"error_code":429,"code_kind":"http","retryable":true}') + cmd, _ = stub(d, err, rc=3, count=calls) + p, _, _, _ = run("unused", extra_env={"POTETO_JUDGE_CMD": cmd}) + row = json.loads(p.stdout)["row"] + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual(row["poteto_lean"], "unavailable") + self.assertIn("RESOURCE_EXHAUSTED", row["poteto_reason"]) + with open(calls) as f: + self.assertEqual(len(f.read().split()), 1) + + def test_permanent_errors_and_bad_json_are_not_retried(self): + for out, rc in (("UNAUTHENTICATED (code 401)", 1), ("bad JSON", 0)): + with self.subTest(out=out): + d = tempfile.mkdtemp() + calls = os.path.join(d, "calls") + cmd, _ = stub(d, out, rc=rc, count=calls) + p, _, _, _ = run("unused", extra_env={"POTETO_JUDGE_CMD": cmd}) + self.assertEqual(json.loads(p.stdout)["row"]["poteto_lean"], "unavailable") + with open(calls) as f: + self.assertEqual(len(f.read().split()), 1) + def test_row_carries_bot_and_model_for_the_scorecard(self): p, _, _, _ = run(GOOD) row = json.loads(p.stdout)["row"]