#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Request the NEXT assignment for this run (the brief's 'call GET /start once'). Bounded adapter, because neither pinned tool has a post-join request path: `sahx.py register` is registration-only and refuses a second call for the same run (one launch id per joining instruction, by design), and v1's `register` is the same request shape. Protocol rule followed here: subsequent requests use this run's X-Session and X-Department and OMIT the registration-only X-Instruction-URL. The outgoing request is persisted before networking; a lost response stays uncertain and is retried with the same X-Request-ID and the same URL, never with a new session. Usage: python next_assignment.py [--dry-run] """ import hashlib import json import os import sys import urllib.error import urllib.request # The credential location is DERIVED, never hard-coded. Fixed 2026-09-17 on job #1595: this line used # to spell out one machine's absolute per-user path (a home directory plus AppData/Local), which the # SERVER detected at submission and which cannot run anywhere else -- a file a return carries but that # nobody can execute, the same defect class as a document a lane cannot act on. Resolution order: the # documented environment variables first (a relocation is then a one-variable change with no edit), # then the platform's own per-user data directory, then the POSIX equivalent. Deliberately identical # to file_audit.py's resolution, so the two tools cannot disagree about where the credential is. def credential_file(): for var in ("SOLVEATHOME_TOKEN_FILE", "SOLVEATHOME_CREDENTIALS"): p = os.environ.get(var) if p: return p if os.path.isfile(p) else os.path.join(p, "twin-primes.token") base = os.environ.get("LOCALAPPDATA") or os.path.join(os.path.expanduser("~"), ".local", "share") return os.path.join(base, "solveathome", "credentials", "twin-primes.token") TOKEN_FILE = credential_file() def sha(p): return hashlib.sha256(open(p, "rb").read()).hexdigest() def settled_job(state, job): """Is this job settled, by EITHER receipt convention? Found live 2026-09-17, immediately after this adapter's own epoch fix: the guard asked for `receipts/.json` while the filer writes `receipts/.json` (with `job_id` inside). Both are local artefacts of the same event, and requiring one spelling made a filed return look unsettled -- which is not a harmless mismatch: it makes the guard refuse the next legitimate take, exactly the defect class the epoch fix was written to remove. The reader now accepts either spelling, so a tool that files by return id and a tool that takes by job id cannot disagree. `state/receipts/.json` is still honoured first so no existing behaviour changes. """ rd = os.path.join(state, "receipts") if os.path.exists(os.path.join(rd, "%s.json" % job)): return True try: names = os.listdir(rd) except OSError: return False for n in names: if not n.endswith(".json"): continue try: rec = json.load(open(os.path.join(rd, n), encoding="utf-8")) except Exception: # noqa: BLE001 - an unreadable receipt must not read as settled continue if str(rec.get("job_id")) == str(job) and (rec.get("return_id") or rec.get("status")): return True return False def append_ledger(run, entry): """Restate the take in the shape the pinned outstanding checker folds on. WHY (found in real use, third window it bit). `sahtool.py outstanding` folds `state/ledger.jsonl` on exactly two kinds, `issued` (keyed by attempt_id) and `receipt`. This adapter recorded takes as `kind: assignment` only, so the checker read a false clean while attempts were taken, worked and filed: it reported `issued 18 / settled 18 / outstanding []` while six later attempts had come and gone. The row written here is a restatement of the server's own answer (its job_id and attempt_id), never an invented attempt. """ p = os.path.join(run, "state", "ledger.jsonl") with open(p, "a", encoding="utf-8", newline="\n") as fh: fh.write(json.dumps(entry, ensure_ascii=False, sort_keys=True) + "\n") def write_json_atomic(path, obj): tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8", newline="\n") as fh: json.dump(obj, fh, indent=1, ensure_ascii=False, sort_keys=True) fh.write("\n") fh.flush() os.fsync(fh.fileno()) os.replace(tmp, path) def main(run, dry=False): st = os.path.join(run, "state") rr = json.load(open(os.path.join(st, "run.json"), encoding="utf-8")) if not rr.get("session") or not rr.get("department_id"): raise SystemExit("run.json has no session/department: this run has not joined") url = "https://solveathome.org/projects/%s/start" % rr["project"] headers = {"Accept": "application/json", "X-Model": rr["model"], "X-Effort": rr["effort"], "X-Session": rr["session"], "X-Department": rr["department_id"], "X-Launch-ID": rr["launch_id"]} assert "X-Instruction-URL" not in headers, "registration-only header must be omitted" # REQUEST-ID MUST ADVANCE PER TAKE, AND MUST NOT ADVANCE PER RETRY. Found live 2026-09-17: # the id was sha256(launch_id | next | url) -- a CONSTANT -- so the first take's op file blocked # every later take for the life of the run ('this run already requested the next assignment'), # while every earlier window worked around it with a fresh-label fetch_full GET /start. A tool # whose brief says 'call GET /start once' and whose guard then forbids the second call is the # same defect class as the stale documents this window audited: it prescribes an action it will # not perform. The fix keeps idempotency where it matters -- a lost response is retried with the # SAME id -- and advances the epoch only once the previous take is SETTLED (a receipt exists for # the job it took). An unsettled take is retried, never re-taken. epoch = 1 while True: rid = hashlib.sha256((rr["launch_id"] + "|next|%d|" % epoch + url) .encode()).hexdigest()[:24] opf = os.path.join(st, "ops", "next-%s.json" % rid) if not os.path.exists(opf): break prev = json.load(open(opf, encoding="utf-8")) prev_job = (prev.get("response") or {}).get("job_id") if prev.get("sent") and prev_job and settled_job(st, prev_job): epoch += 1 # previous take settled (either receipt spelling): a new take is legit continue break # unsettled or unsent: fall through to the guard/retry path op = {"tool": "adapter/next_assignment for sah-tools/1.0.1", "method": "GET", "url": url, "headers": headers, "request_id": rid, "at": __import__("datetime").datetime.now(__import__("datetime").timezone.utc) .strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z", "attempt_id_context": None, "sent": False} if os.path.exists(opf) and not dry: prev = json.load(open(opf, encoding="utf-8")) pj = prev.get("response", {}).get("job_id") if prev.get("sent") and pj and not settled_job(st, pj): print(json.dumps({"ok": False, "stage": "guard", "reason": "this take's request was sent and its job is NOT settled " "(no receipt naming it, by job id or by return id): retry it " "with --retry rather than taking a new assignment, so a lost " "response cannot double-take", "op": opf, "job_id": pj, "receipt_expected": "state/receipts/%s.json or any receipt whose " "job_id is %s" % (pj, pj)}, indent=1)) return 2 write_json_atomic(opf, op) # persist BEFORE networking if dry: print(json.dumps({"ok": True, "dry_run": True, "op": opf, "headers": sorted(headers)}, indent=1)) return 0 tok = open(TOKEN_FILE, encoding="utf-8").read().strip() req = urllib.request.Request(url, headers=dict(headers, Authorization="Bearer " + tok)) try: with urllib.request.urlopen(req, timeout=120) as r: code, body = r.status, r.read().decode("utf-8", "replace") except urllib.error.HTTPError as e: code, body = e.code, e.read().decode("utf-8", "replace") except Exception as e: code, body = 0, "ERR %s" % e if code == 0: write_json_atomic(opf, dict(op, sent=True, uncertain=True, last_error=body[:200])) print(json.dumps({"ok": False, "stage": "network", "uncertain": True, "next_action": "retry the SAME request id %s, never a new session" % rid}, indent=1)) return 1 try: j = json.loads(body) except Exception: j = None if code == 200 and isinstance(j, dict) and j.get("job_id"): att = j.get("attempt_id") write_json_atomic(opf, dict(op, sent=True, response={"code": code, "job_id": j["job_id"], "attempt_id": att, "type": j.get("type")})) write_json_atomic(os.path.join(st, "next-assignment.json"), {"tool": "adapter/next_assignment", "at": op["at"], "request_id": rid, "http_status": code, "response": j, "response_sha256": hashlib.sha256(body.encode()).hexdigest()}) if att: os.makedirs(os.path.join(run, "assignments"), exist_ok=True) with open(os.path.join(run, "assignments", "%s.md" % att), "w", encoding="utf-8", newline="\n") as fh: fh.write(j.get("brief_md") or "") if att: append_ledger(run, {"at": op["at"], "kind": "issued", "attempt_id": att, "job_id": j["job_id"], "type": j.get("type"), "bucket": j.get("research_bucket"), "research_route_id": j.get("research_route_id"), "research_stage": j.get("research_stage"), "expires": j.get("expires"), "request_id": rid, "via": "adapter/next_assignment (post-join GET /start)", "note": "restated in the shape sahtool.py outstanding folds on; " "without it the checker reads a false clean for this path"}) print(json.dumps({"ok": True, "job_id": j["job_id"], "type": j.get("type"), "attempt_id": att, "run_id": j.get("run_id"), "session": j.get("session"), "session_jobs": j.get("session_jobs"), "research_stage": j.get("research_stage"), "brief_bytes": len(j.get("brief_md") or ""), "op": opf, "dry_run": False}, indent=1)) return 0 write_json_atomic(opf, dict(op, sent=True, response={"code": code, "body": body[:600]})) print(json.dumps({"ok": False, "stage": "server", "http_status": code, "body": body[:400], "request_id": rid, "next_action": "inspect; do not open a new session"}, indent=1)) return 1 if __name__ == "__main__": a = sys.argv[1:] sys.exit(main(a[0], "--dry-run" in a))