burtenshaw's picture
burtenshaw HF Staff
fix: stop automation outside august
14cfb77 verified
Raw History Blame Contribute Delete
18 kB
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "huggingface_hub>=1.19.0,<2",
# "requests>=2.32.0",
# "requests-oauthlib>=2.0.0",
# ]
# ///
"""X publisher and reply reviewer for the August 2026 agent handover.
Live posting is opt-in. Without LIVE_POSTING=true the publish command selects
and prints the next post but never calls X. Raw replies and publication state
are written only to a private Hugging Face dataset repository.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
from collections import Counter, defaultdict
from datetime import date, datetime
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from zoneinfo import ZoneInfo
import requests
from huggingface_hub import HfApi, hf_hub_download
from requests_oauthlib import OAuth1
CONTROL_REPO_ID = os.environ.get(
"CONTROL_REPO_ID", "burtenshaw/agent-handover-control"
)
CONTROL_REPO_TYPE = "dataset"
X_API_BASE = os.environ.get("X_API_BASE", "https://api.x.com/2")
URL_RE = re.compile(r"https://[^\s]+")
CAMPAIGN_SLUGS = {"campaign"}
def load_json(path: Path) -> dict[str, Any]:
return json.loads(path.read_text())
def dump_json(payload: dict[str, Any]) -> str:
return json.dumps(payload, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
def bool_env(name: str, default: bool = False) -> bool:
value = os.environ.get(name)
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
def hf_token() -> str | None:
return os.environ.get("HF_TOKEN") or None
def hub_json(filename: str, default: dict[str, Any] | None = None) -> dict[str, Any]:
try:
path = hf_hub_download(
repo_id=CONTROL_REPO_ID,
repo_type=CONTROL_REPO_TYPE,
filename=filename,
token=hf_token(),
)
except Exception:
if default is not None:
return default
raise
return load_json(Path(path))
def upload_hub_json(filename: str, payload: dict[str, Any], message: str) -> None:
HfApi(token=hf_token()).upload_file(
repo_id=CONTROL_REPO_ID,
repo_type=CONTROL_REPO_TYPE,
path_in_repo=filename,
path_or_fileobj=dump_json(payload).encode("utf-8"),
commit_message=message,
)
def load_queue(path: Path | None) -> dict[str, Any]:
return load_json(path) if path else hub_json("queue.json")
def load_state(path: Path | None) -> dict[str, Any]:
default = {
"version": 1,
"last_mention_id": None,
"last_review_at": None,
"feedback_scores": {},
"published": {},
"published_post_ids": [],
}
if path:
return load_json(path)
return hub_json("state.json", default=default)
def save_state(path: Path | None, state: dict[str, Any], message: str) -> None:
if path:
path.write_text(dump_json(state))
else:
upload_hub_json("state.json", state, message)
def campaign_today(queue: dict[str, Any], override: str | None = None) -> date:
if override:
return date.fromisoformat(override)
timezone = ZoneInfo(queue["campaign"]["timezone"])
return datetime.now(timezone).date()
def validate_queue(
queue: dict[str, Any],
catalogue: dict[str, Any] | None = None,
check_urls: bool = False,
) -> None:
campaign = queue["campaign"]
start = date.fromisoformat(campaign["start_date"])
end = date.fromisoformat(campaign["end_date"])
expected_count = (end - start).days + 1
posts = queue["posts"]
errors: list[str] = []
if len(posts) != expected_count:
errors.append(f"expected {expected_count} posts, found {len(posts)}")
ids = [post["id"] for post in posts]
if len(ids) != len(set(ids)):
errors.append("post ids are not unique")
texts = [post["text"] for post in posts]
if len(texts) != len(set(texts)):
errors.append("post text is not unique")
catalogue_slugs = CAMPAIGN_SLUGS
if catalogue is not None:
catalogue_slugs = CAMPAIGN_SLUGS | {
item["slug"]
for item in catalogue["experiments"]
if item.get("publishable")
}
urls: set[str] = set()
for post in posts:
raw_length = len(post["text"])
if raw_length > 280:
errors.append(f"{post['id']} is {raw_length} raw characters")
if post["status"] not in {"ready", "hold", "disabled"}:
errors.append(f"{post['id']} has invalid status {post['status']}")
if post["source_slug"] not in catalogue_slugs:
errors.append(
f"{post['id']} references missing/unpublishable {post['source_slug']}"
)
not_before = date.fromisoformat(post["not_before"])
if not (start <= not_before <= end):
errors.append(f"{post['id']} not_before is outside campaign")
if post.get("fixed_date"):
fixed = date.fromisoformat(post["fixed_date"])
if not (start <= fixed <= end):
errors.append(f"{post['id']} fixed_date is outside campaign")
post_urls = URL_RE.findall(post["text"])
if not post_urls:
errors.append(f"{post['id']} has no public evidence URL")
urls.update(post_urls)
if check_urls:
session = requests.Session()
session.headers["User-Agent"] = "agent-handover-validator/1.0"
for url in sorted(urls):
try:
response = session.get(url, timeout=20, allow_redirects=True)
if response.status_code >= 400:
errors.append(f"URL {url} returned {response.status_code}")
except requests.RequestException as exc:
errors.append(f"URL {url} failed: {type(exc).__name__}")
if errors:
raise SystemExit("queue validation failed:\n- " + "\n- ".join(errors))
print(
f"queue_valid posts={len(posts)} start={start} end={end} "
f"urls_checked={check_urls}",
flush=True,
)
def x_credentials_available() -> bool:
return all(
os.environ.get(name)
for name in (
"X_API_KEY",
"X_API_SECRET",
"X_ACCESS_TOKEN",
"X_ACCESS_TOKEN_SECRET",
)
)
def x_session() -> requests.Session:
missing = [
name
for name in (
"X_API_KEY",
"X_API_SECRET",
"X_ACCESS_TOKEN",
"X_ACCESS_TOKEN_SECRET",
)
if not os.environ.get(name)
]
if missing:
raise SystemExit("missing X OAuth secrets: " + ", ".join(missing))
session = requests.Session()
session.auth = OAuth1(
os.environ["X_API_KEY"],
os.environ["X_API_SECRET"],
os.environ["X_ACCESS_TOKEN"],
os.environ["X_ACCESS_TOKEN_SECRET"],
)
session.headers.update({"User-Agent": "agent-handover-august-2026/1.0"})
return session
def x_request(
session: requests.Session,
method: str,
path: str,
**kwargs: Any,
) -> dict[str, Any]:
response = session.request(method, f"{X_API_BASE}{path}", timeout=30, **kwargs)
if response.status_code >= 400:
excerpt = response.text[:1000].replace("\n", " ")
raise RuntimeError(
f"X API {method} {path} returned {response.status_code}: {excerpt}"
)
return response.json()
def classify_reply(text: str) -> list[str]:
lowered = text.lower()
labels: list[str] = []
groups = {
"reproduction_issue": (
"reproduce",
"error",
"failed",
"doesn't work",
"does not work",
"install",
"command",
"traceback",
),
"experiment_suggestion": (
"try ",
"what about",
"could you",
"would you",
"next experiment",
"compare",
"rerun",
),
"method_question": (
"why",
"how",
"which",
"what ",
"?",
),
"claim_challenge": (
"not enough",
"leak",
"overfit",
"baseline",
"significance",
"cherry",
"invalid",
),
}
for label, terms in groups.items():
if any(term in lowered for term in terms):
labels.append(label)
return labels or ["reaction"]
def review_replies(
queue: dict[str, Any],
state: dict[str, Any],
state_path: Path | None,
date_override: str | None = None,
) -> None:
today = campaign_today(queue, date_override)
start = date.fromisoformat(queue["campaign"]["start_date"])
end = date.fromisoformat(queue["campaign"]["end_date"])
if not (start <= today <= end):
print(f"review_skipped date={today} reason=outside_campaign", flush=True)
return
if not x_credentials_available():
print("review_skipped reason=missing_x_oauth_credentials", flush=True)
return
session = x_session()
me = x_request(session, "GET", "/users/me", params={"user.fields": "username"})
user_id = me["data"]["id"]
params: dict[str, Any] = {
"max_results": 100,
"tweet.fields": (
"author_id,conversation_id,created_at,in_reply_to_user_id,"
"public_metrics,referenced_tweets"
),
"expansions": "author_id",
"user.fields": "username,name",
}
if state.get("last_mention_id"):
params["since_id"] = state["last_mention_id"]
payload = x_request(session, "GET", f"/users/{user_id}/mentions", params=params)
replies = payload.get("data", [])
users = {
user["id"]: user
for user in payload.get("includes", {}).get("users", [])
}
label_counts: Counter[str] = Counter()
feedback: defaultdict[str, float] = defaultdict(float)
reviewed: list[dict[str, Any]] = []
for reply in replies:
text = reply.get("text", "")
labels = classify_reply(text)
label_counts.update(labels)
metrics = reply.get("public_metrics", {})
weight = 1.0 + min(float(metrics.get("like_count", 0)), 5.0) * 0.1
lowered = text.lower()
matched_slugs: set[str] = set()
for post in queue["posts"]:
if any(keyword.lower() in lowered for keyword in post["keywords"]):
matched_slugs.add(post["source_slug"])
for slug in matched_slugs:
feedback[slug] += weight
author = users.get(reply.get("author_id"), {})
reviewed.append(
{
"id": reply.get("id"),
"created_at": reply.get("created_at"),
"conversation_id": reply.get("conversation_id"),
"author_id": reply.get("author_id"),
"author_username": author.get("username"),
"text": text,
"labels": labels,
"matched_slugs": sorted(matched_slugs),
"public_metrics": metrics,
}
)
existing_scores = state.setdefault("feedback_scores", {})
for slug, increment in feedback.items():
existing_scores[slug] = round(float(existing_scores.get(slug, 0)) + increment, 4)
if replies:
state["last_mention_id"] = max(reply["id"] for reply in replies)
now = datetime.now(ZoneInfo("UTC")).isoformat()
state["last_review_at"] = now
review_record = {
"reviewed_at": now,
"account": me["data"],
"count": len(reviewed),
"label_counts": dict(label_counts),
"feedback_increments": dict(feedback),
"replies": reviewed,
}
if state_path:
output = state_path.parent / "latest_reply_review.json"
output.write_text(dump_json(review_record))
else:
stamp = datetime.now(ZoneInfo("UTC")).strftime("%Y%m%dT%H%M%SZ")
upload_hub_json(
f"reply_reviews/{stamp}.json",
review_record,
f"review X replies {stamp}",
)
save_state(state_path, state, "update X reply review state")
print(
f"replies_reviewed={len(reviewed)} labels={dict(label_counts)} "
f"feedback={dict(feedback)}",
flush=True,
)
def select_post(
queue: dict[str, Any], state: dict[str, Any], today: date
) -> dict[str, Any]:
today_text = today.isoformat()
published_ids = set(state.get("published_post_ids", []))
if today_text in state.get("published", {}):
raise SystemExit(f"a post is already recorded for {today_text}")
fixed = [
post
for post in queue["posts"]
if post.get("fixed_date") == today_text
and post["status"] == "ready"
and post["id"] not in published_ids
]
if fixed:
if len(fixed) != 1:
raise SystemExit(f"multiple fixed posts found for {today_text}")
return fixed[0]
eligible = [
post
for post in queue["posts"]
if post["status"] == "ready"
and post["id"] not in published_ids
and not post.get("fixed_date")
and date.fromisoformat(post["not_before"]) <= today
]
if not eligible:
raise SystemExit(f"no eligible post for {today_text}")
feedback_scores = state.get("feedback_scores", {})
eligible.sort(
key=lambda post: (
-float(post.get("manual_priority", 0)),
-float(feedback_scores.get(post["source_slug"], 0)),
int(post["sequence"]),
)
)
return eligible[0]
def publish(
queue: dict[str, Any],
state: dict[str, Any],
state_path: Path | None,
date_override: str | None,
force_dry_run: bool,
) -> None:
today = campaign_today(queue, date_override)
start = date.fromisoformat(queue["campaign"]["start_date"])
end = date.fromisoformat(queue["campaign"]["end_date"])
if not (start <= today <= end):
print(f"publish_skipped date={today} reason=outside_campaign", flush=True)
return
post = select_post(queue, state, today)
live = bool_env("LIVE_POSTING") and not force_dry_run
if not live:
print(
dump_json(
{
"mode": "dry_run",
"date": today.isoformat(),
"selected": post,
"reason": "LIVE_POSTING is not true" if not force_dry_run else "--dry-run",
}
),
end="",
)
return
if not x_credentials_available():
raise SystemExit("LIVE_POSTING=true but X OAuth credentials are missing")
payload: dict[str, Any] = {"text": post["text"]}
if bool_env("X_MADE_WITH_AI", default=True):
payload["made_with_ai"] = True
response = x_request(x_session(), "POST", "/tweets", json=payload)
post_id = response["data"]["id"]
username = os.environ.get("X_USERNAME", "i")
post_url = f"https://x.com/{username}/status/{post_id}"
record = {
"date": today.isoformat(),
"published_at": datetime.now(ZoneInfo("UTC")).isoformat(),
"post_id": post_id,
"post_url": post_url,
"queue_id": post["id"],
"source_slug": post["source_slug"],
"text": post["text"],
"x_response": response,
}
state.setdefault("published", {})[today.isoformat()] = record
state.setdefault("published_post_ids", []).append(post["id"])
if state_path:
(state_path.parent / f"published-{today.isoformat()}.json").write_text(
dump_json(record)
)
else:
upload_hub_json(
f"published/{today.isoformat()}-{post['id']}.json",
record,
f"record X post {today.isoformat()}",
)
save_state(state_path, state, f"record X post state {today.isoformat()}")
print(f"published post_id={post_id} queue_id={post['id']} url={post_url}", flush=True)
def show_status(queue: dict[str, Any], state: dict[str, Any]) -> None:
ready = [post for post in queue["posts"] if post["status"] == "ready"]
published = state.get("published_post_ids", [])
print(
dump_json(
{
"campaign": queue["campaign"],
"ready": len(ready),
"published": len(published),
"remaining": len(ready) - len(published),
"last_review_at": state.get("last_review_at"),
"feedback_scores": state.get("feedback_scores", {}),
"live_posting": bool_env("LIVE_POSTING"),
"x_credentials_available": x_credentials_available(),
}
),
end="",
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=("validate", "review", "publish", "status"))
parser.add_argument("--queue", type=Path)
parser.add_argument("--state", type=Path)
parser.add_argument("--catalogue", type=Path)
parser.add_argument("--check-urls", action="store_true")
parser.add_argument("--date", help="ISO date override for validation/dry-run tests")
parser.add_argument("--dry-run", action="store_true")
return parser.parse_args()
def main() -> None:
args = parse_args()
queue = load_queue(args.queue)
state = load_state(args.state)
catalogue = load_json(args.catalogue) if args.catalogue else None
if args.command == "validate":
validate_queue(queue, catalogue=catalogue, check_urls=args.check_urls)
elif args.command == "review":
review_replies(queue, state, args.state, args.date)
elif args.command == "publish":
publish(queue, state, args.state, args.date, args.dry_run)
elif args.command == "status":
show_status(queue, state)
else: # pragma: no cover
raise AssertionError(args.command)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)