From 7b72d662b85f2a639dc6bea7546f89c5cdd26c71 Mon Sep 17 00:00:00 2001 From: Pip Date: Sun, 22 Nov 2026 14:48:12 +1100 Subject: [PATCH] review: a screen for the watch list and the event descriptions Pip, 2026-11-22: "a screen based html tool for me to render decisions on those monthly events", and for the descriptions, "I want to read each one, at least to scan it with human eyes. Let's make that tool." scripts/review/serve_review.py, a local server bound to 127.0.0.1, with three tabs: - Watch triage: all 110 atoms, with sources, retrieval status, scan flags and duplicate hints in view before the decision. Keys a/b/x/?. - Month end: accept / reject (a reason is required) / keep watching. The producer's own gate is asked before an accept is recorded. - Descriptions: what is served now beside the arXiv abstract, exactly as it would be served, plus how pdoom1 shows the record today. An optional EDITORIAL condensation is stored as attributed opinion beside the abstract and never served as the description (ADR-001 ignore-a-field). One implementation of every decision: the mutation logic in triage_watch.py and review_descriptions.py is extracted into apply_triage / apply_decide / apply_note / build_decision, and both front ends call those functions. The keyboard tools behave as before. Refuses a foreign Origin, and refuses to start a second instance: during testing a buffered first start looked dead, and the second one took the next port with its own in-memory copy of the watch list. tests/test_serve_review.py runs the real server against temp copies (16 cases) and is wired into check_all and CI. Also: a fresh arXiv fetch of all 1,129 records (152 titles differ, 0 lose characters). _metadata.json is tracked; data.jsonl is ignored, as for every dump of this adapter. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/data-integrity.yml | 3 + .../dumps/2026-11-22_034213/_metadata.json | 48 +++ scripts/review/review_descriptions.py | 53 ++- scripts/review/serve_review.py | 293 ++++++++++++++ scripts/review/serve_review_page.html | 379 ++++++++++++++++++ scripts/review/triage_watch.py | 137 ++++--- scripts/validation/check_all.py | 6 + tests/test_serve_review.py | 133 ++++++ 8 files changed, 987 insertions(+), 65 deletions(-) create mode 100644 data/raw/arxiv_abstracts/dumps/2026-11-22_034213/_metadata.json create mode 100644 scripts/review/serve_review.py create mode 100644 scripts/review/serve_review_page.html create mode 100644 tests/test_serve_review.py diff --git a/.github/workflows/data-integrity.yml b/.github/workflows/data-integrity.yml index 872f57c..8bd6d21 100644 --- a/.github/workflows/data-integrity.yml +++ b/.github/workflows/data-integrity.yml @@ -151,6 +151,9 @@ jobs: - name: The source portability gate can still fail run: python tests/test_source_portability.py + - name: Screen review writes what the keyboard tools write + run: python tests/test_serve_review.py + - name: Serveable zone matches a fresh build (candidates) run: python scripts/build/project_candidates.py --check diff --git a/data/raw/arxiv_abstracts/dumps/2026-11-22_034213/_metadata.json b/data/raw/arxiv_abstracts/dumps/2026-11-22_034213/_metadata.json new file mode 100644 index 0000000..b5f6a69 --- /dev/null +++ b/data/raw/arxiv_abstracts/dumps/2026-11-22_034213/_metadata.json @@ -0,0 +1,48 @@ +{ + "source_id": "arxiv_abstracts", + "dump_stamp": "2026-11-22_034213", + "fetched_at": "2026-11-22T03:42:13.559579+00:00", + "api": "http://export.arxiv.org/api/query", + "requested": 1129, + "retrieved": 1129, + "not_returned": [], + "license": { + "spdx": "CC0-1.0", + "url": "https://creativecommons.org/publicdomain/zero/1.0/", + "attribution": "arXiv.org. Abstracts are authored text, offered by arXiv as descriptive metadata. Attributed here as a courtesy that CC0 does not require.", + "citation": "arXiv API (export.arxiv.org/api/query), Atom summary field", + "source_terms_url": "https://info.arxiv.org/help/api/tou.html", + "verified_at": "2026-08-21", + "verified_by": "Fetched and read the arXiv API Terms of Use and its footnote 1 defining descriptive metadata; see the comment above this constant for both quotations." + }, + "transformations": [ + { + "step": "whitespace_collapse", + "what": "runs of whitespace and newlines collapsed to single spaces", + "why": "arXiv wraps the abstract for display; the wrapping is not content", + "lossy": false + }, + { + "step": "ascii_coerce", + "what": "_base.to_ascii, NFKD decomposition with no '?' fallback", + "why": "the repository is ASCII-only and enforces it in CI", + "lossy": true, + "note": "an accented letter survives as its base letter; a character with no ASCII decomposition is DELETED, which is why chars_dropped is recorded per record and shown to the reviewer before the choice" + }, + { + "step": "sentence_trim", + "what": "cut at the last sentence boundary at or before 600 characters", + "why": "event_v1 allows 1000; 600 is an editorial choice, not a schema requirement, so it is named here as a choice", + "lossy": true, + "note": "applied only when the abstract exceeds the limit; is_excerpt records it" + } + ], + "audit_chain": [ + "served description", + "<- data/curated/event_descriptions/decisions.jsonl (named reviewer, exact approved string)", + "<- this dump's data.jsonl, field abstract (verbatim, unmodified)", + "<- entry_id, the versioned arXiv Atom entry this was read from", + "<- the paper itself at source_url" + ], + "note": "Abstracts for records in enriched_alignment_research_events.json, which has no raw provenance in this repo. See pdoom-data#88." +} diff --git a/scripts/review/review_descriptions.py b/scripts/review/review_descriptions.py index b38829c..370ec34 100644 --- a/scripts/review/review_descriptions.py +++ b/scripts/review/review_descriptions.py @@ -115,6 +115,43 @@ def append_decision(entry): handle.write(json.dumps(entry, ensure_ascii=True, sort_keys=True) + "\n") +def build_decision(p, verdict, proposed, by, proposals_file, editorial=None): + """One decision row. Shared by this keyboard tool and serve_review.py. + + `editorial` is Pip's own condensation of the abstract, when he writes one. + It is an ATTRIBUTED OPINION, held beside the source's words and never in + place of them: the overlay in project_timeline_events.py reads only + `description`, which is always the abstract exactly as shown. A consumer + that wants the shorter text (pdoom1, for in-game display) can take + `editorial`; one that does not can ignore the key. That is ADR-001's + fork-or-ignore test passed on purpose. Ruled by Pip 2026-11-22: "I will + want to note that it's been editorialised by me rather than the raw + extract". + """ + if verdict not in [v[0] for v in KEYS.values()]: + raise ValueError("unknown verdict %r" % verdict) + if not (by or "").strip(): + raise ValueError("no anonymous verdicts") + row = { + "id": p["id"], + "arxiv_id": p["arxiv_id"], + "source_url": p["source_url"], + "verdict": verdict, + "description": proposed if verdict == "accept_abstract" else None, + "replaces": p["current_description"], + "reviewer": by, + "at": datetime.now(timezone.utc).isoformat(), + "proposals_file": proposals_file, + "title_matches": p.get("title_matches"), + "chars_dropped": p.get("chars_dropped") or [], + } + text = " ".join((editorial or "").split()) + if text: + row["editorial"] = {"text": text, "by": by, + "kind": "editorialised -- not the source's words"} + return row + + def render(p, position, total, proposed): print("\n" + "=" * 78) print("[%d/%d] %s" % (position, total, p["current_title"][:64])) @@ -204,19 +241,9 @@ def main(): continue verdict, _label = KEYS[key] - append_decision({ - "id": p["id"], - "arxiv_id": p["arxiv_id"], - "source_url": p["source_url"], - "verdict": verdict, - "description": proposed if verdict == "accept_abstract" else None, - "replaces": p["current_description"], - "reviewer": args.by, - "at": datetime.now(timezone.utc).isoformat(), - "proposals_file": os.path.relpath(args.proposals, REPO).replace("\\", "/"), - "title_matches": p.get("title_matches"), - "chars_dropped": p.get("chars_dropped") or [], - }) + append_decision(build_decision( + p, verdict, proposed, args.by, + os.path.relpath(args.proposals, REPO).replace("\\", "/"))) counts[verdict] = counts.get(verdict, 0) + 1 print("\n%d decision(s) recorded by %s: %s" diff --git a/scripts/review/serve_review.py b/scripts/review/serve_review.py new file mode 100644 index 0000000..b05546e --- /dev/null +++ b/scripts/review/serve_review.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +"""Screen-based review: the watch list and the event descriptions, in a browser. + + python scripts/review/serve_review.py --by "Pip Foweraker" + python scripts/review/serve_review.py --by "..." --proposals /data.jsonl + python scripts/review/serve_review.py --by "..." --port 8741 --no-browser + +Opens a local page (127.0.0.1 only) with three tabs: + + WATCH TRIAGE all 110 atoms. a / b / x / ? exactly as triage_watch.py. + MONTH END atoms already on Watch. Accept / reject (reason required, + because it is published) / keep watching. + DESCRIPTIONS arXiv abstract beside what is served now. Accept / keep / + undecided, with an optional EDITORIAL condensation that is + stored as attributed opinion and never served as the + description. + +Why a browser and not the keyboard tools +---------------------------------------- +Asked for by Pip on 2026-11-22: "a screen based html tool for me to render +decisions", for a sitting where he wants to read every item with human eyes +and see its sourcing before deciding how far to trust it. The keyboard tools +show one atom in 74 columns and hide the sources behind the description; for a +judgement about sourcing, the sources are the thing to look at. + +One implementation of every decision +------------------------------------ +This file decides NOTHING about what a key means. Watch mutations are +`triage_watch.apply_triage / apply_decide / apply_note`, description rows are +`review_descriptions.build_decision`, and the promotion warning is +`triage_watch.gate_reasons`, which imports the producer's own gate. The +keyboard tools call the same functions. So the two front ends cannot drift: +there is no second copy to drift. + +Every action is written to disk before the page updates -- the watch list and +its append-only log, or decisions.jsonl -- so closing the tab, killing the +server or losing power costs nothing already clicked. + +Do not run this and triage_watch.py at the same time. Each holds the watch +list in memory and rewrites the whole file on every decision, so the second +writer would silently undo the first one's work. +""" +import argparse +import glob +import io +import json +import os +import socket +import sys +import threading +import webbrowser +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +sys.path.insert(0, os.path.join(REPO, "scripts", "review")) + +import triage_watch as tw # noqa: E402 +import review_descriptions as rd # noqa: E402 + +ABSTRACT_DUMPS = os.path.join(REPO, "data", "raw", "arxiv_abstracts", "dumps") +EVENTS = os.path.join(REPO, "data", "serveable", "api", "timeline_events", + "all_events.json") + + +def newest_proposals(): + """The newest arXiv abstract dump that actually holds its data.jsonl. + + data.jsonl is gitignored for this adapter (real abstracts carry non-ASCII + the gate would reject), so a dump directory can exist on a seat with only + its _metadata.json. Measured on Bort 2026-11-22: four dump dirs, one with + data. Picking by directory name alone would pick an empty one. + """ + found = sorted(glob.glob(os.path.join(ABSTRACT_DUMPS, "*", "data.jsonl"))) + return found[-1] if found else None + + +class State(object): + def __init__(self, by, proposals_path): + self.by = by + self.lock = threading.Lock() + self.rows = tw.load() if os.path.isfile(tw.WATCHLIST) else [] + self.by_id = {r["id"]: r for r in self.rows} + self.proposals_path = proposals_path + self.proposals = rd.load_proposals(proposals_path) if proposals_path else [] + self.prop_by_id = {p["id"]: p for p in self.proposals} + self.titles = {} + if os.path.isfile(EVENTS): + with io.open(EVENTS, encoding="utf-8") as handle: + events = json.load(handle) + for key, ev in (events.items() if isinstance(events, dict) + else ((e.get("id"), e) for e in events)): + self.titles[key] = ev.get("title") or ev.get("name") + + def rel(self, path): + return os.path.relpath(path, REPO).replace("\\", "/") + + # ---- watch ---- + def watch_payload(self): + return {"by": self.by, "rows": self.rows, + "triage_keys": {k: [v[0], v[1], v[2]] for k, v in tw.KEYS.items()}, + "decide_keys": {k: [v[0], v[1]] for k, v in tw.DECIDE_KEYS.items()}} + + def triage(self, atom_id, key): + if key not in tw.KEYS: + raise ValueError("unknown triage key %r" % key) + with self.lock: + row = self.by_id[atom_id] + tw.apply_triage(self.rows, row, key, self.by) + return row + + def note(self, atom_id, note): + note = " ".join((note or "").split()) + if not note: + raise ValueError("empty note") + with self.lock: + row = self.by_id[atom_id] + tw.apply_note(self.rows, row, note, self.by) + return row + + def gate(self, atom_id): + return tw.gate_reasons(self.by_id[atom_id], self.by) + + def decide(self, atom_id, status, note): + with self.lock: + row = self.by_id[atom_id] + tw.apply_decide(self.rows, row, status, (note or "").strip() or None, + self.by) + return row + + # ---- descriptions ---- + def descriptions_payload(self): + decided = rd.load_decisions() + items = [] + for p in self.proposals: + items.append({ + "id": p["id"], + "arxiv_id": p.get("arxiv_id"), + "source_url": p.get("source_url"), + "current_title": p.get("current_title"), + "arxiv_title": p.get("arxiv_title"), + "title_matches": p.get("title_matches"), + "chars_dropped": p.get("chars_dropped") or [], + "current_description": p.get("current_description"), + "proposed": rd.trim(p.get("abstract_ascii")), + "full_abstract": p.get("abstract_ascii"), + "served_title": self.titles.get(p["id"]) or p.get("current_title"), + "decision": decided.get(p["id"]), + }) + return {"by": self.by, + "proposals_file": self.rel(self.proposals_path) if self.proposals_path else None, + "keys": {k: [v[0], v[1]] for k, v in rd.KEYS.items()}, + "items": items} + + def describe(self, record_id, verdict, editorial): + p = self.prop_by_id[record_id] + row = rd.build_decision(p, verdict, rd.trim(p.get("abstract_ascii")), + self.by, self.rel(self.proposals_path), editorial) + with self.lock: + rd.append_decision(row) + return row + + +def make_handler(state, page): + class Handler(BaseHTTPRequestHandler): + def log_message(self, fmt, *args): # quiet: the page is the feedback + pass + + def _send(self, code, body, ctype="application/json"): + data = body if isinstance(body, bytes) else body.encode("ascii") + self.send_response(code) + self.send_header("Content-Type", ctype + "; charset=us-ascii") + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + + def _json(self, code, obj): + self._send(code, json.dumps(obj, ensure_ascii=True)) + + def do_GET(self): + if self.path == "/": + return self._send(200, page, "text/html") + if self.path == "/api/watch": + return self._json(200, state.watch_payload()) + if self.path == "/api/descriptions": + return self._json(200, state.descriptions_payload()) + return self._json(404, {"error": "no such path"}) + + def do_POST(self): + # Same-origin only. The server binds 127.0.0.1, but a page on any + # other site can still POST to localhost; refusing a foreign + # Origin closes that. + origin = self.headers.get("Origin") + host = "http://%s" % self.headers.get("Host", "") + if origin and origin != host: + return self._json(403, {"error": "foreign origin refused"}) + try: + length = int(self.headers.get("Content-Length") or 0) + body = json.loads(self.rfile.read(length).decode("utf-8") or "{}") + if self.path == "/api/watch/triage": + out = state.triage(body["id"], body["key"]) + elif self.path == "/api/watch/note": + out = state.note(body["id"], body["note"]) + elif self.path == "/api/watch/gate": + out = {"reasons": state.gate(body["id"])} + elif self.path == "/api/watch/decide": + out = state.decide(body["id"], body["status"], body.get("note")) + elif self.path == "/api/descriptions/decide": + out = state.describe(body["id"], body["verdict"], + body.get("editorial")) + else: + return self._json(404, {"error": "no such path"}) + except (KeyError, ValueError) as exc: + return self._json(400, {"error": str(exc)}) + return self._json(200, out) + return Handler + + +def running_instance(start, span=50): + """URL of a serve_review already listening near `start`, else None. + + Found the hard way on 2026-11-22: a first start whose stdout was buffered + looked dead, a second start took the next free port, and two servers each + held the watch list in memory. Either one's next write would have silently + reverted the other's. A second instance is refused, not tolerated. + """ + import urllib.request + for port in range(start, start + span): + url = "http://127.0.0.1:%d/" % port + try: + with urllib.request.urlopen(url + "api/watch", timeout=0.3) as r: + if r.status == 200 and b'"triage_keys"' in r.read(): + return url + except Exception: + continue + return None + + +def free_port(start): + for port in range(start, start + 50): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + if s.connect_ex(("127.0.0.1", port)) != 0: + return port + raise SystemExit("no free port in %d-%d" % (start, start + 49)) + + +PAGE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), + "serve_review_page.html") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--by", required=True, + help="reviewer name. Required -- no anonymous verdicts") + ap.add_argument("--proposals", + help="arXiv abstract dump data.jsonl (default: newest with data)") + ap.add_argument("--port", type=int, default=8741) + ap.add_argument("--no-browser", action="store_true") + args = ap.parse_args() + + proposals = args.proposals or newest_proposals() + if proposals and not os.path.isfile(proposals): + sys.stderr.write("no such proposals file: %s\n" % proposals) + return 2 + state = State(args.by.strip(), proposals) + with io.open(PAGE_PATH, encoding="ascii") as handle: + page = handle.read() + + already = running_instance(args.port) + if already: + sys.stderr.write("a review server is already running at %s -- open that " + "one. Two would each rewrite the watch list and undo " + "each other.\n" % already) + return 3 + port = free_port(args.port) + url = "http://127.0.0.1:%d/" % port + httpd = ThreadingHTTPServer(("127.0.0.1", port), make_handler(state, page)) + print("review server for %s at %s" % (state.by, url), flush=True) + print(" watch list: %d atom(s)" % len(state.rows)) + print(" descriptions: %d proposal(s) from %s" + % (len(state.proposals), state.rel(proposals) if proposals else "NONE")) + print("every click is on disk before the page updates. Ctrl-C to stop.", flush=True) + if not args.no_browser: + threading.Timer(0.4, lambda: webbrowser.open(url)).start() + try: + httpd.serve_forever() + except KeyboardInterrupt: + print("\nstopped. nothing was in flight.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/review/serve_review_page.html b/scripts/review/serve_review_page.html new file mode 100644 index 0000000..bf86c77 --- /dev/null +++ b/scripts/review/serve_review_page.html @@ -0,0 +1,379 @@ + + + + + +pdoom-data review + + + +
+

pdoom-data review

+ + + + + loading +
+
+
+
+ + +
+
+
+
+

Loading.

+
+ + + diff --git a/scripts/review/triage_watch.py b/scripts/review/triage_watch.py index 4139c38..2518f7d 100644 --- a/scripts/review/triage_watch.py +++ b/scripts/review/triage_watch.py @@ -152,6 +152,88 @@ def append_log(entry): handle.write(json.dumps(entry, ensure_ascii=True, sort_keys=True) + "\n") +def _now(): + return datetime.now(timezone.utc).isoformat() + + +# --------------------------------------------------------------------------- +# The three mutations, ONE implementation each. +# +# Until 2026-11-22 these lived inline in the two keyboard loops below. A +# browser front end (scripts/review/serve_review.py) needs exactly the same +# semantics, and a second copy of "what does pressing b do to an atom" would be +# a variant the moment either side changed -- the failure gate_reasons() below +# already documents for the promotion rules. Both front ends call these. Each +# appends to the log BEFORE mutating and saves after, so a crash loses the atom +# file, never the record. +# --------------------------------------------------------------------------- + +def apply_triage(rows, row, key, by, today=None): + """Triage key a/b/x/? -> rating + watch_status. Returns the log entry.""" + today = today or date.today().isoformat() + rating, status, _label = KEYS[key] + entry = { + "id": row["id"], + "prev": {"rating": row.get("rating"), + "watch_status": row.get("watch_status")}, + "next": {"rating": rating, "watch_status": status}, + "by": by, + "at": _now(), + } + append_log(entry) + row["rating"] = rating + row["watch_status"] = status + if status == "watching": + row["watching_since"] = row.get("watching_since") or today + row["decided_on"] = None + row["decided_by"] = None + elif status == "rejected": + row["decided_on"] = today + row["decided_by"] = by + else: + row["watching_since"] = None + save(rows) + return entry + + +def apply_decide(rows, row, status, note, by, today=None): + """Month-end: accepted / rejected (note required) / watching.""" + if status not in [v[0] for v in DECIDE_KEYS.values()]: + raise ValueError("unknown decide status %r" % status) + if status in ("accepted", "rejected") and not (note or "").strip(): + raise ValueError("accept and reject both require a reason") + today = today or date.today().isoformat() + entry = { + "id": row["id"], + "pass": "decide", + "prev": {"watch_status": row.get("watch_status"), + "decision_note": row.get("decision_note")}, + "next": {"watch_status": status, "decision_note": note}, + "by": by, + "at": _now(), + } + append_log(entry) + row["watch_status"] = status + if status == "watching": + row["decided_on"] = None + row["decided_by"] = None + else: + row["decided_on"] = today + row["decided_by"] = by + row["decision_note"] = note + save(rows) + return entry + + +def apply_note(rows, row, note, by): + entry = {"id": row["id"], "field": "note", "value": note, + "by": by, "at": _now()} + append_log(entry) + row["note"] = note + save(rows) + return entry + + def render(row, position, total): flags = [] if not row["sources"]: @@ -272,27 +354,7 @@ def decide_loop(args, rows, queue): print(" (left alone)") continue - prior = {"watch_status": row.get("watch_status"), - "decision_note": row.get("decision_note")} - append_log({ - "id": row["id"], - "pass": "decide", - "prev": prior, - "next": {"watch_status": status, "decision_note": note}, - "by": args.by, - "at": datetime.now(timezone.utc).isoformat(), - }) - - row["watch_status"] = status - if status == "watching": - row["decided_on"] = None - row["decided_by"] = None - else: - row["decided_on"] = today - row["decided_by"] = args.by - row["decision_note"] = note - - save(rows) + apply_decide(rows, row, status, note, args.by, today) decided += 1 print("\n%d decision(s) recorded by %s." % (decided, args.by)) @@ -397,42 +459,13 @@ def main(): continue note = input(" note> ").strip() if note: - by_id[last]["note"] = note - append_log({"id": last, "field": "note", "value": note, - "by": args.by, - "at": datetime.now(timezone.utc).isoformat()}) - save(rows) + apply_note(rows, by_id[last], note, args.by) continue if key not in KEYS: print(" (unrecognised key, nothing changed)") continue - rating, status, _label = KEYS[key] - prior = {"rating": row.get("rating"), - "watch_status": row.get("watch_status")} - - # Log BEFORE mutating, so a crash loses the atom file, never the record. - append_log({ - "id": row["id"], - "prev": prior, - "next": {"rating": rating, "watch_status": status}, - "by": args.by, - "at": datetime.now(timezone.utc).isoformat(), - }) - - row["rating"] = rating - row["watch_status"] = status - if status == "watching": - row["watching_since"] = row.get("watching_since") or today - row["decided_on"] = None - row["decided_by"] = None - elif status == "rejected": - row["decided_on"] = today - row["decided_by"] = args.by - else: - row["watching_since"] = None - - save(rows) + apply_triage(rows, row, key, args.by, today) decided += 1 last = row["id"] diff --git a/scripts/validation/check_all.py b/scripts/validation/check_all.py index aa88b73..5bf76d7 100644 --- a/scripts/validation/check_all.py +++ b/scripts/validation/check_all.py @@ -125,6 +125,12 @@ ["scripts/validation/check_source_portability.py"], True), ("source portability gate can still fail", ["tests/test_source_portability.py"], True), + # The browser review front end writes human judgement into data/curated/, + # which nothing can rebuild. It must write exactly what the keyboard tools + # write, refuse an empty reason and a foreign Origin, and keep an + # editorial condensation out of the served description. + ("screen review writes what the keyboard tools write", + ["tests/test_serve_review.py"], True), ] REBUILD = [ diff --git a/tests/test_serve_review.py b/tests/test_serve_review.py new file mode 100644 index 0000000..0fd5f39 --- /dev/null +++ b/tests/test_serve_review.py @@ -0,0 +1,133 @@ +"""The screen review server writes exactly what the keyboard tools write. + + python tests/test_serve_review.py + +Runs the real HTTP server on a free localhost port against TEMPORARY copies of +the watch list, its log and decisions.jsonl, so nothing here can touch a real +judgement. Asserts: + + * triage keys set the same fields triage_watch.KEYS says they set, and log first; + * month-end accept/reject refuse an empty reason (the reason is published); + * a description decision carries the reviewer, serves the trimmed abstract, + and an editorial is stored BESIDE the description, never in place of it; + * the overlay the timeline build applies ignores the editorial entirely; + * a POST from a foreign Origin is refused (a web page can POST to localhost). +""" +import io +import json +import os +import shutil +import sys +import tempfile +import threading +import urllib.error +import urllib.request + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(REPO, "scripts", "review")) +sys.path.insert(0, os.path.join(REPO, "scripts", "build")) + +import triage_watch as tw # noqa: E402 +import review_descriptions as rd # noqa: E402 +import serve_review as sr # noqa: E402 + +FAILURES = [] + + +def check(label, cond, detail=""): + print((" ok " if cond else " FAIL ") + label + ("" if cond or not detail else " -- " + detail)) + if not cond: + FAILURES.append(label) + + +def post(base, path, body, origin=None): + data = json.dumps(body).encode("ascii") + req = urllib.request.Request(base + path, data=data, method="POST", + headers={"Content-Type": "application/json"}) + if origin: + req.add_header("Origin", origin) + try: + with urllib.request.urlopen(req) as r: + return r.status, json.loads(r.read().decode("ascii")) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read().decode("ascii")) + + +def main(): + tmp = tempfile.mkdtemp(prefix="serve_review_test_") + try: + watch = os.path.join(tmp, "candidates.jsonl") + shutil.copy(tw.WATCHLIST, watch) + tw.WATCHLIST, tw.LOG = watch, os.path.join(tmp, "triage_log.jsonl") + rd.DECISIONS_DIR = tmp + rd.DECISIONS = os.path.join(tmp, "decisions.jsonl") + + proposal = {"id": "test:paper", "arxiv_id": "0000.00000", "source_url": "https://arxiv.org/abs/0000.00000", + "current_title": "A Paper", "arxiv_title": "A Paper", "title_matches": True, + "chars_dropped": [], "current_description": "1 Introduction\n----", + "abstract_ascii": "We study a thing. " * 60} + props = os.path.join(tmp, "data.jsonl") + with io.open(props, "w", encoding="ascii", newline="\n") as h: + h.write(json.dumps(proposal) + "\n") + + state = sr.State("Test Reviewer", props) + state.rel = lambda p: os.path.basename(p) + httpd = sr.ThreadingHTTPServer(("127.0.0.1", sr.free_port(18741)), sr.make_handler(state, "")) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + base = "http://127.0.0.1:%d" % httpd.server_address[1] + + print("watch triage") + atom = state.rows[0]["id"] + code, row = post(base, "/api/watch/triage", {"id": atom, "key": "a"}) + check("a puts the atom on Watch with rating A", code == 200 and row["rating"] == "A" and row["watch_status"] == "watching", str(row)[:120]) + check("watching clears decided_by", row.get("decided_by") is None) + with io.open(tw.LOG, encoding="ascii") as h: + log = [json.loads(l) for l in h] + check("the log holds the decision, attributed", log and log[-1]["by"] == "Test Reviewer" and log[-1]["next"]["rating"] == "A") + on_disk = {json.loads(l)["id"]: json.loads(l) for l in io.open(watch, encoding="ascii")} + check("the atom file is rewritten on disk", on_disk[atom]["watch_status"] == "watching") + code, _ = post(base, "/api/watch/triage", {"id": atom, "key": "z"}) + check("an unknown key is refused", code == 400) + + print("month end") + code, body = post(base, "/api/watch/decide", {"id": atom, "status": "accepted", "note": " "}) + check("accept without a reason is refused", code == 400, str(body)) + code, row = post(base, "/api/watch/decide", {"id": atom, "status": "rejected", "note": "tertiary source only"}) + check("reject with a reason records it and the decider", code == 200 and row["decision_note"] == "tertiary source only" and row["decided_by"] == "Test Reviewer") + code, body = post(base, "/api/watch/gate", {"id": atom}) + check("the producer's gate answers", code == 200 and isinstance(body.get("reasons"), list), str(body)[:120]) + + print("descriptions") + code, row = post(base, "/api/descriptions/decide", {"id": "test:paper", "verdict": "accept_abstract", + "editorial": " Short version. "}) + check("accept serves the trimmed abstract", code == 200 and row["description"] == rd.trim(proposal["abstract_ascii"])) + check("the trim is at most 600 chars", len(row["description"]) <= 604) + check("the editorial is stored beside it, attributed", + row.get("editorial", {}).get("text") == "Short version." and row["editorial"]["by"] == "Test Reviewer") + check("the description is NOT the editorial", row["description"] != "Short version.") + import project_timeline_events as pte + pte.CURATED_DESCRIPTIONS = rd.DECISIONS + overlay = pte.load_description_overlay([]) + check("the build overlay serves the abstract, not the editorial", + overlay.get("test:paper", {}).get("description") == row["description"]) + code, row = post(base, "/api/descriptions/decide", {"id": "test:paper", "verdict": "keep_current"}) + check("keep_current carries no description and no editorial", row["description"] is None and "editorial" not in row) + + print("origin") + code, body = post(base, "/api/watch/triage", {"id": atom, "key": "b"}, origin="https://evil.example") + check("a foreign Origin is refused", code == 403, str(body)) + check("and changed nothing", state.by_id[atom]["watch_status"] == "rejected") + + httpd.shutdown() + finally: + shutil.rmtree(tmp, ignore_errors=True) + + if FAILURES: + print("\n%d case(s) failed." % len(FAILURES)) + return 1 + print("\nserve_review: every front-end write matches the shared implementation.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())