diff --git a/fastinsight/pipeline.py b/fastinsight/pipeline.py index b14c97e..3757b89 100644 --- a/fastinsight/pipeline.py +++ b/fastinsight/pipeline.py @@ -309,11 +309,6 @@ def confirmation_text(result: Dict[str, Any]) -> str: direction = " / ".join(direction_names) or str(route.get("matched_direction") or "").strip() or "未分类" delivered = result.get("delivered") or [] names: List[str] = [] - for owner in route.get("owners") or []: - if isinstance(owner, dict) and owner.get("name"): - name = str(owner["name"]).strip() - if name and name not in names: - names.append(name) for item in delivered: if not isinstance(item, dict): continue diff --git a/scripts/auto_pipeline.py b/scripts/auto_pipeline.py index 7f6d507..16bc524 100644 --- a/scripts/auto_pipeline.py +++ b/scripts/auto_pipeline.py @@ -22,6 +22,7 @@ sys.path.insert(0, str(ROOT)) from text_clip import compose_research_summary, prefer_abstract from service_auth import service_configuration, service_token +from publish_receipt import validate_publish_receipt ROSTER_DEFAULT = ROOT.parent / "assets" / "colleagues.yaml" @@ -54,30 +55,28 @@ def _verification_query(paper, title): return " ".join(piece for piece in pieces if piece) -def _merge_web_fallback(existing, fallback): - """Keep screenshot/link metadata and enrich gaps from a web-search hit.""" - merged = dict(existing) - existing_url = _text(merged.get("url")) - score = fallback.get("match_score") +def _accepted_candidate(candidate): + if candidate.get("exact"): + return True try: - strong_match = float(score or 0) >= 0.6 + return 0.6 <= float(candidate.get("match_score") or 0) <= 1.0 except (TypeError, ValueError): - strong_match = False + return False + + +def _merge_web_fallback(existing, fallback): + """Fetching a candidate does not grant it authority over the supplied paper.""" + merged = dict(existing) + if not _accepted_candidate(fallback): + merged["verification_note"] = "unconfirmed search candidate; supplied paper metadata retained" + return merged page_fetched = bool(fallback.get("page_fetched")) - for key in ("url", "url_kind"): - value = fallback.get(key) - if value is None or value == "": - continue - if not existing_url or strong_match or page_fetched: - merged[key] = value - for key in ("provider", "match_score", "web_search_result"): + for key in ("url", "url_kind", "provider", "match_score", "web_search_result"): value = fallback.get(key) if value is not None and value != "": merged[key] = value if page_fetched: - # A successfully fetched page is the source of truth for metadata: - # use the title/authors/venue/year found on the page. Abstracts still - # prefer an official paper abstract over a search snippet. + # Only an accepted candidate may replace supplied metadata. for key in ("title", "authors", "year", "venue", "doi", "arxiv_id"): if _text(fallback.get(key)): merged[key] = fallback[key] @@ -144,7 +143,7 @@ def _publish(endpoint, ingest_key, person, paper, trends, direction, *, cas_conf method="POST", ) with urllib.request.urlopen(request, timeout=20) as response: - return json.loads(response.read().decode("utf-8")) + return validate_publish_receipt(json.loads(response.read().decode("utf-8"))) def _normalize_paper(paper): @@ -163,13 +162,9 @@ def _apply_verification(paper, verified): if not isinstance(verified, dict) or not isinstance(verified.get("best"), dict): return paper best = verified["best"] - try: - score = float(best.get("match_score") or 0) - except (TypeError, ValueError): - score = 0.0 academic_confirmed = bool( verified.get("verified_by_academic_sources") - and (best.get("exact") or score >= 0.6) + and _accepted_candidate(best) ) if academic_confirmed: return best diff --git a/scripts/publish_receipt.py b/scripts/publish_receipt.py new file mode 100644 index 0000000..e439973 --- /dev/null +++ b/scripts/publish_receipt.py @@ -0,0 +1,12 @@ +"""The FastResearch publish response contract shared by both publishing entries.""" + + +def validate_publish_receipt(receipt): + if not isinstance(receipt, dict) or receipt.get("ok") is not True: + raise ValueError("FastResearch publish receipt must be an object with ok=true") + names = receipt.get("deliveredTo") + if not isinstance(names, list) or not names or any( + not isinstance(name, str) or not name.strip() for name in names + ): + raise ValueError("FastResearch publish receipt requires a nonempty deliveredTo list of names") + return receipt diff --git a/scripts/publish_to_research.py b/scripts/publish_to_research.py index 8cf0440..ba9b9fa 100644 --- a/scripts/publish_to_research.py +++ b/scripts/publish_to_research.py @@ -11,6 +11,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from text_clip import compose_research_summary, normalize_ws from service_auth import service_configuration, service_token +from publish_receipt import validate_publish_receipt def normalize(value): @@ -106,11 +107,14 @@ def main(): ) try: with urllib.request.urlopen(request, timeout=15) as response: - print(response.read().decode("utf-8", "replace")) + receipt = validate_publish_receipt(json.loads(response.read().decode("utf-8"))) + print(json.dumps(receipt, ensure_ascii=False)) except urllib.error.HTTPError as error: raise SystemExit( f"FastResearch 发布失败 ({error.code}): {error.read().decode('utf-8', 'replace')}" ) + except ValueError as error: + raise SystemExit(f"FastResearch 发布失败:{error}") if __name__ == "__main__": diff --git a/tests/http_world.py b/tests/http_world.py new file mode 100644 index 0000000..7d29b03 --- /dev/null +++ b/tests/http_world.py @@ -0,0 +1,115 @@ +import json +import os +import tempfile +import threading +import urllib.parse +import urllib.request +from contextlib import ExitStack +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from unittest.mock import patch + +from tests.transport.http_transport import route_urlopen + + +class HTTPWorld: + """External academic/search/model/Research protocols; production internals stay real.""" + def __init__(self): + self.title = "Unrelated astronomy observations" + self.receipts = {} + self.published = [] + self.requests = [] + self.model_entered = threading.Event() + self.model_release = threading.Event() + self.model_release.set() + world = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + self.respond() + + def do_POST(self): + self.respond() + + def respond(self): + target = self.headers.get("X-Fixture-Url", self.path) + path = urllib.parse.urlsplit(target).path + body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + world.requests.append(target) + status, content_type = 200, "application/json" + if path.endswith("/chat/completions"): + world.model_entered.set() + if not world.model_release.wait(10): + status, value = 500, {"error": "fixture model was not released"} + else: + value = {"choices": [{"message": {"content": "A fixture trend summary."}}]} + elif path == "/api/insight/publish": + payload = json.loads(body) + world.published.append(payload) + value = world.receipts.get(payload.get("person"), { + "ok": True, "deliveredTo": [payload.get("person", "A")], + }) + elif "serpapi.com" in target: + value = {"organic_results": [{"title": world.title, + "link": "https://papers.example/discovered", "snippet": "Search abstract"}]} + elif "papers.example" in target: + content_type = "text/html" + value = (f'
' + '' + '' + '') + elif "api.crossref.org" in target: + value = {"message": {"items": []}} + elif "api.openalex.org" in target: + value = {"results": []} + elif "semanticscholar.org" in target: + value = {"data": []} + elif "arxiv.org" in target: + content_type, value = "application/atom+xml", '