From 6e66f6f81bbb1cf5b724fc435cc85a76e112d450 Mon Sep 17 00:00:00 2001 From: XxFran10xX <318299142+XxFran10xX@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:08:12 +0100 Subject: [PATCH 1/2] Weekly post: right numbers, three passes, and who wrote it - Facts give the level-1 value of class numbers that a limit can cut, show new classes in full and put the same change to many items on one line. - The post is written, improved and checked. The Friday run gets 45 minutes. - Number changes that no fact or note shows go to the check and to staff. - Short Discord messages are joined, and the post aims for about 1,400 words. - The review says who wrote the post and how often it was checked. - When Claude is out of usage on Friday, the post is tried again until 15:15 before Codex writes it. - The replaced version of a post can be put back, and a posted week is only written again when asked. - Work for the staff team is left out of the facts; Mage Staffs are not. Co-Authored-By: Claude Opus 5.5 --- backend/src/api/patchnotes_routes.py | 83 +++++++++++--- .../src/api/test_patchnotes_post_routes.py | 65 ++++++++++- backend/src/patchnotes/compose.py | 104 +++++++++++++++--- backend/src/patchnotes/db.py | 94 +++++++++++++--- backend/src/patchnotes/number_check.py | 50 +++++++++ backend/src/patchnotes/rewrite_worker.py | 96 +++++++++++++--- backend/src/patchnotes/test_compose.py | 28 ++++- backend/src/patchnotes/test_db.py | 49 ++++++++- backend/src/patchnotes/test_number_check.py | 45 ++++++++ backend/src/patchnotes/test_rewrite_worker.py | 70 ++++++++++-- backend/src/patchnotes/test_weekly.py | 53 +++++++++ backend/src/patchnotes/test_weekly_run.py | 22 ++++ backend/src/patchnotes/weekly.py | 90 ++++++++++++--- backend/src/patchnotes/weekly_run.py | 34 +++++- discord/patchnotes/README.md | 7 +- discord/patchnotes/format.py | 35 +++++- discord/patchnotes/patchnotes.py | 66 ++++++++++- discord/patchnotes/test_cancel.py | 66 +++++++++++ discord/patchnotes/test_format.py | 17 +++ docs/docs/ops/patch-notes-jobs.md | 10 +- 20 files changed, 982 insertions(+), 102 deletions(-) create mode 100644 backend/src/patchnotes/number_check.py create mode 100644 backend/src/patchnotes/test_number_check.py diff --git a/backend/src/api/patchnotes_routes.py b/backend/src/api/patchnotes_routes.py index 9cb912d6..32a1945b 100644 --- a/backend/src/api/patchnotes_routes.py +++ b/backend/src/api/patchnotes_routes.py @@ -10,7 +10,7 @@ import logging import os import uuid -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Any, Literal from fastapi import APIRouter, Depends, Header, HTTPException, Request @@ -24,6 +24,7 @@ feedback_review_prompt, review_prompt, fallback_messages, + improve_prompt, messages_from_response, ) from src.patchnotes.db import ( @@ -36,6 +37,7 @@ PatchnotesConfigError, PatchnotesDBError, TOPICS, + WEEKLY_REQUESTER, WeekNotPostponed, WeekPostponed, add_folder_rule, @@ -53,6 +55,7 @@ drop_bullet, ensure_folder, finish_job, + friday, get_act, get_bullet, get_facts, @@ -89,6 +92,8 @@ list_player_notes, recent_posts, remove_player_note, + requeue_job, + restore_post, save_post, set_act, undo_postpone, @@ -150,7 +155,6 @@ def _client_detail(exc: Exception) -> str: return "Patch notes request failed. Check server logs." -WEEKLY_REQUESTER = "weekly" def _iso(value: Any) -> str | None: @@ -849,6 +853,7 @@ def _job_payload(row: dict[str, Any]) -> dict[str, Any]: "feedback": row.get("feedback"), "created_at": _iso(row.get("created_at")), "finished_at": _iso(row.get("finished_at")), + "retry_at": _iso(row.get("not_before")), } @@ -945,10 +950,10 @@ def staff_claim_job(): if job is None: return {"job": None} if job["kind"] == "compose": - prompt, review = _post_prompts(job) + prompt, improve, review = _post_prompts(job) return { - "job": _job_payload(job), "prompt": prompt, "schema": POST_SCHEMA, "review": review, - "requester": job.get("requester"), + "job": _job_payload(job), "prompt": prompt, "schema": POST_SCHEMA, "improve": improve, + "review": review, "requester": job.get("requester"), "may_wait": _retry_at(job) is not None, } lines = _job_lines(job) if job["kind"] == "feedback": @@ -967,6 +972,12 @@ def staff_claim_job(): class JobResultBody(BaseModel): output: str | None = None error: str | None = None + # The first writer is out of usage and asks to be tried again later. + retry: bool = False + writer: str | None = Field(default=None, max_length=80) + checks: int = Field(default=0, ge=0, le=10) + # Post lines with number changes the facts do not show: [line, numbers]. + unconfirmed: list[tuple[str, str]] = Field(default_factory=list, max_length=200) @patchnotes_router.post("/staff/jobs/{job_id}/result", dependencies=[Depends(_staff_guard)]) @@ -1089,8 +1100,8 @@ def _note_lines(week: str) -> list[str]: return [note["body"] for note in list_player_notes(week)] -def _post_prompts(job: dict[str, Any]) -> tuple[str, str]: - """The writing prompt and the one for checking its draft.""" +def _post_prompts(job: dict[str, Any]) -> tuple[str, str | None, str]: + """The writing prompt, the one for improving its draft and the one for checking it.""" week = job["week"] stored = get_facts(week) feedback = (job.get("feedback") or "").strip() or None @@ -1110,8 +1121,31 @@ def _post_prompts(job: dict[str, Any]) -> tuple[str, str]: notes=_note_lines(week), ) if previous and feedback: - return prompt, feedback_review_prompt(previous, feedback) - return prompt, review_prompt(prompt) + return prompt, None, feedback_review_prompt(previous, feedback) + return prompt, improve_prompt(prompt), review_prompt(prompt) + + +_RETRY_EVERY = timedelta(hours=1) +# The last try starts early enough for staff to review the post before 18:00. +_LAST_RETRY = (15, 15) +_MAX_UNCONFIRMED = 5 + + +def _retry_at(job: dict[str, Any], now: datetime | None = None) -> datetime | None: + """When a Friday run whose first writer is out of usage may try again, if there is time.""" + if job.get("requester") != WEEKLY_REQUESTER or job.get("kind") != "compose": + return None + moment = (now or datetime.now(timezone.utc)) + _RETRY_EVERY + return moment if moment <= friday(job["week"], *_LAST_RETRY) else None + + +def _post_report(body: JobResultBody, messages: list[str]) -> dict[str, Any] | None: + """Who wrote the post and which of its lines staff should look at.""" + if not body.writer: + return None + text = "\n".join(messages) + lines = [[line, numbers] for line, numbers in body.unconfirmed if line.strip() and line in text] + return {"writer": body.writer, "checks": body.checks, "unconfirmed": lines[:_MAX_UNCONFIRMED]} def _save_fallback(week: str) -> dict[str, Any] | None: @@ -1128,11 +1162,14 @@ def _save_fallback(week: str) -> dict[str, Any] | None: def _finish_post_job(job: dict[str, Any], body: JobResultBody) -> dict[str, Any]: """Store the writer's post. A failure keeps the last post, or a plain one from the facts.""" job_id = str(job["id"]) + if body.retry and job.get("requester") == WEEKLY_REQUESTER: + # Past the last try it is claimed again at once, and then the next writer takes it. + return requeue_job(job_id, _retry_at(job) or datetime.now(timezone.utc)) try: - if body.error is not None: - raise FeedbackError(body.error.strip()[:300] or "The rewrite agent failed.") - messages = messages_from_response(_json_object(body.output or "")) - save_post(job["week"], messages, "writer") + if body.error is not None or body.retry: + raise FeedbackError((body.error or "").strip()[:300] or "The rewrite agent failed.") + messages = messages_from_response(_json_object(body.output or ""), pack=not job.get("feedback")) + save_post(job["week"], messages, "writer", _post_report(body, messages)) return finish_job(job_id, changed=len(messages)) except (FeedbackError, ValueError) as e: row = finish_job(job_id, error=str(e)[:300]) @@ -1150,6 +1187,8 @@ def _post_payload(week: str, post: dict[str, Any] | None, job: dict[str, Any] | "source": post["source"] if post else None, "status": post["status"] if post else "composing", "updated_at": _iso(post.get("updated_at")) if post else None, + "report": post.get("report") if post else None, + "has_previous": bool(post and post.get("has_previous")), "job": _job_payload(job) if job else None, } @@ -1255,6 +1294,24 @@ def staff_week_post_compose(week: str, body: RequesterBody | None = None): return {"job": _job_payload(job)} +@patchnotes_router.post("/staff/weeks/{week}/post/restore", dependencies=[Depends(_staff_guard)]) +def staff_week_post_restore(week: str): + """Put back the version the last write replaced. Doing it again swaps back.""" + week_key = _week_or_400(week) + try: + migrate() + job = latest_job(week_key, POST_JOB_KINDS) + if job is not None and job["status"] in {"queued", "running"}: + raise HTTPException(status_code=409, detail="The post is already being written.") + post = restore_post(week_key) + if post is None: + raise HTTPException(status_code=404, detail="There is no earlier version of this post.") + return _post_payload(week_key, post, job) + except (PatchnotesDBError, PatchnotesConfigError, database.Error) as e: + logger.exception("staff_week_post_restore failed") + raise HTTPException(status_code=502, detail=_client_detail(e)) from e + + class PlayerNoteBody(BaseModel): body: str = Field(..., min_length=1, max_length=600) author: str = Field(default="", max_length=60) diff --git a/backend/src/api/test_patchnotes_post_routes.py b/backend/src/api/test_patchnotes_post_routes.py index a939c36a..b64e0318 100644 --- a/backend/src/api/test_patchnotes_post_routes.py +++ b/backend/src/api/test_patchnotes_post_routes.py @@ -22,7 +22,8 @@ from fastapi.testclient import TestClient # noqa: E402 from server import app # noqa: E402 -from src.patchnotes.db import JobActive # noqa: E402 +from src.api import patchnotes_routes as routes # noqa: E402 +from src.patchnotes.db import JobActive, PatchnotesDBError # noqa: E402 _HEADERS = {"X-Staff-Key": "dev-staff-key"} _ROUTES = "src.api.patchnotes_routes" @@ -116,6 +117,8 @@ def test_the_writer_gets_the_notes_and_a_check(self) -> None: data = self.client.post("/patchnotes/staff/jobs/claim", headers=_HEADERS).json() self.assertIn("- Horses are faster.", data["prompt"]) self.assertTrue(data["review"].startswith(data["prompt"])) + self.assertTrue(data["improve"].startswith(data["prompt"])) + self.assertFalse(data["may_wait"]) def test_facts_are_stored_and_start_the_writer(self) -> None: with mock.patch(f"{_ROUTES}.save_facts") as save, mock.patch( @@ -247,8 +250,64 @@ def test_writer_result_is_stored_as_a_draft(self) -> None: headers=_HEADERS, ) self.assertEqual(response.status_code, 200) - save.assert_called_once_with("2026-W41", ["# Update 5.3\nHi", "# Fixes\n- Fixed knockouts"], "writer") - finish.assert_called_once_with("22222222-2222-2222-2222-222222222222", changed=2) + # Short messages are joined, and an older worker does not say who wrote it. + save.assert_called_once_with("2026-W41", ["# Update 5.3\nHi\n\n# Fixes\n- Fixed knockouts"], "writer", None) + finish.assert_called_once_with("22222222-2222-2222-2222-222222222222", changed=1) + + def test_staff_learn_who_wrote_it_and_which_numbers_to_check(self) -> None: + messages = ["# Update 5.3", "- Bash 9 --> 7 s"] + body = {"output": json.dumps({"messages": messages}), "writer": "claude:claude-opus-5-5", "checks": 2, + "unconfirmed": [["- Bash 9 --> 7 s", "9 --> 7"], ["- Removed 2 --> 1 s", "2 --> 1"]]} + report = {"writer": "claude:claude-opus-5-5", "checks": 2, "unconfirmed": [["- Bash 9 --> 7 s", "9 --> 7"]]} + url = "/patchnotes/staff/jobs/22222222-2222-2222-2222-222222222222/result" + # A rewrite after feedback keeps the messages as staff asked for them. + for feedback, stored in ((None, ["# Update 5.3\n\n- Bash 9 --> 7 s"]), ("Split it", messages)): + with mock.patch(f"{_ROUTES}.get_job", return_value=_job(status="running", feedback=feedback)), mock.patch( + f"{_ROUTES}.save_post" + ) as save, mock.patch(f"{_ROUTES}.finish_job", return_value=_job(status="done")): + self.assertEqual(self.client.post(url, json=body, headers=_HEADERS).status_code, 200) + save.assert_called_once_with("2026-W41", stored, "writer", report) + with mock.patch(f"{_ROUTES}.get_post", return_value=_post(report=report, has_previous=True)), mock.patch( + f"{_ROUTES}.latest_job", return_value=_job(status="done") + ): + post = self.client.get("/patchnotes/staff/weeks/2026-W41/post", headers=_HEADERS).json() + self.assertEqual((post["report"], post["has_previous"], post["job"]["retry_at"]), (report, True, None)) + + def test_a_friday_run_out_of_usage_is_tried_again_while_there_is_time(self) -> None: + url = "/patchnotes/staff/jobs/22222222-2222-2222-2222-222222222222/result" + early = datetime(2026, 10, 9, 10, 10, tzinfo=timezone.utc) # 12:10 in Berlin + late = datetime(2026, 10, 9, 12, 20, tzinfo=timezone.utc) + weekly = _job(status="running", requester="weekly") + self.assertEqual(routes._retry_at(weekly, early), datetime(2026, 10, 9, 11, 10, tzinfo=timezone.utc)) + self.assertIsNone(routes._retry_at(weekly, late)) + self.assertIsNone(routes._retry_at(_job(requester="42"), early)) + self.assertIsNone(routes._retry_at(_job(requester="weekly", kind="sort"), early)) + for job, moment, requeued in ((weekly, early, True), (weekly, None, True), (_job(status="running"), None, False)): + with mock.patch(f"{_ROUTES}.get_job", return_value=job), mock.patch( + f"{_ROUTES}._retry_at", return_value=moment + ), mock.patch(f"{_ROUTES}.requeue_job", return_value=_job(not_before=early)) as requeue, mock.patch( + f"{_ROUTES}.finish_job", return_value=_job(status="failed") + ) as finish, mock.patch(f"{_ROUTES}.get_post", return_value=_post()): + body = self.client.post(url, json={"retry": True}, headers=_HEADERS).json() + self.assertEqual((requeue.called, finish.called), (requeued, not requeued)) + self.assertEqual(body["job"]["retry_at"] is not None, requeued) + if requeued: + self.assertLessEqual(requeue.call_args.args[1], moment or datetime.now(timezone.utc)) + + def test_the_replaced_version_can_be_put_back(self) -> None: + url = "/patchnotes/staff/weeks/2026-W41/post/restore" + self.assertEqual(self.client.post(url).status_code, 401) + for job, post, status in ( + (_job(status="running"), _post(), 409), (None, None, 404), (_job(status="done"), _post(), 200), + ): + with mock.patch(f"{_ROUTES}.latest_job", return_value=job), mock.patch( + f"{_ROUTES}.restore_post", return_value=post + ): + response = self.client.post(url, headers=_HEADERS) + self.assertEqual(response.status_code, status) + self.assertEqual(response.json()["messages"], ["# Update 5.3\nHello"]) + with mock.patch(f"{_ROUTES}.latest_job", side_effect=PatchnotesDBError("down")): + self.assertEqual(self.client.post(url, headers=_HEADERS).status_code, 502) def test_writer_failure_keeps_a_plain_post(self) -> None: with mock.patch(f"{_ROUTES}.get_job", return_value=_job(status="running")), mock.patch( diff --git a/backend/src/patchnotes/compose.py b/backend/src/patchnotes/compose.py index aa045cb5..44c023f1 100644 --- a/backend/src/patchnotes/compose.py +++ b/backend/src/patchnotes/compose.py @@ -32,7 +32,8 @@ # The bot puts the role ping in front of the first message. FIRST_LIMIT = 1900 # The writer aims for TARGET_MESSAGES. A busy week may run longer, up to MAX_MESSAGES. -TARGET_MESSAGES = 8 +TARGET_MESSAGES = 6 +TARGET_WORDS = 1400 MAX_MESSAGES = 15 _FACTS_BUDGET = 240_000 _MENTION = re.compile(r"@(everyone|here)|<@[!&]?\d+>") @@ -90,8 +91,14 @@ - When many values moved by the same share, say the share once and give the old and new numbers of the ones players know best. Put several changes to one class or item into one bullet. - Write numbers as `Old --> New`. Use only numbers that appear in the facts. Never invent a number or a reason. + Say what a number is: "cooldown 20 --> 17 s". When a whole list is cooldowns, one sentence above it can say so. +- Give a number when it changed or when players need it to act. Other settings, such as a radius or a timer of + something new, are better in words. +- Say who an effect reaches exactly as the facts do: you, your allies, or both. What several classes or items share + belongs to all of them, never to one. When you do not understand what a value means, describe the change in words without the number. A raw modifier - players never see, such as `-55% --> -50%` damage, is better as "hits harder". + players never see, such as `-55% --> -50%` damage or `0.01 --> 0.02` upkeep, is better as "hits harder" or "twice as + much". A share that a whole class gains or loses, such as 15% less magic damage, is fine as a number. - The config changes compare the start of the week with its end, so they are the only full picture: a value that moved several times shows as one step. Write that one step and mention each change once. - Commits, developer descriptions and staff notes are listed oldest first and can hold a value, name or plan that @@ -109,15 +116,17 @@ - Never use an em dash or emojis. - Write only about changes general players notice and care about. Leave out single players, admin and staff commands, the world border, edge-case fixes and technical cleanup. -- Never give drop chances, roll counts, resource costs of hidden systems or creature stats. Say "more", +- Never give drop chances, roll counts, resource costs of hidden systems or creature stats, and never the caps and + exceptions that stop farming, such as an hourly limit or a creature that gives nothing. Say "more", "less", "stronger" or "weaker" instead. Never name new traits or creature tricks. - A passive or effect that only appears in class config may be internal. Describe what players feel, not its name, unless a plugin update line also mentions it. - Features players cannot use yet stay out. If the facts do not show that something is usable, leave it out. - Before answering, check every number, name and behaviour against the facts once more, and delete any line the facts do not clearly support. A shorter post is better than a wrong line. -- Keep the whole post to at most {target} messages. On a busy week, fold small related changes into - one short line each and leave minor ones to the website instead of listing everything. +- Keep the whole post to at most {target} messages and about {words} words, however busy the week is. Fold small related + changes into one short line each, use at most three bullets or sentences on anything few players touch, and leave + minor ones to the website instead of listing everything. - Split the post into Discord messages in order. Each message must stay under 1900 characters. Start a new message at a heading, never in the middle of a list. - Section headings are fixed. Leave a section out only when nothing belongs in it. @@ -130,6 +139,9 @@ - `damage-reduction`, `physical-damage`, `projectile_damage`, `critical_strike_chance` and `weapon_damage` are percentages. `health-regeneration` is health per second. `max-mana` and `mana-regeneration` work the same way. - A skill's `level` in a class is the class level that unlocks it. +- `at level 1` is what players see on a skill at level 1. Those numbers are final. A skill's plain `base` is its value + at level 1 too, and `per-level` is added per skill level. +- One line can list many names that all changed the same way. - `time_modifier(N)` adds N percent to production time, so lower is faster. `prestige(N)` and `upkeep(N)` are Dowsing node values. - `required-class` lists the classes that may use an item. @@ -208,8 +220,10 @@ def _title_rule(label: str, act: str | None) -> str: ("ArmourShop/", 4), ("ItemsAdder/", 4), ) -_FILE_BUDGET = 20_000 -_ENTRY_DETAILS = 30 +_FILE_BUDGET = 30_000 +_ENTRY_DETAILS = 80 +_GROUP_FROM = 3 +_GROUP_NAMES = 15 def _file_rank(path: str) -> int: @@ -219,15 +233,33 @@ def _file_rank(path: str) -> int: return 2 +def _grouped(entries: list[Any]) -> list[tuple[list[str], str, list[str]]]: + """Entries as names, kind and details. Entries that changed the same way become one.""" + groups: dict[tuple[str, tuple[str, ...]], list[str]] = {} + for entry in entries: + if isinstance(entry, dict): + details = tuple(str(detail) for detail in entry.get("details") or []) + groups.setdefault((str(entry.get("kind")), details), []).append(str(entry.get("name"))) + found: list[tuple[list[str], str, list[str]]] = [] + for (kind, details), names in groups.items(): + if len(names) >= _GROUP_FROM and details: + found.append((names, kind, list(details))) + else: + found += [([name], kind, list(details)) for name in names] + return found + + def _render_file(item: dict[str, Any]) -> str: lines = [f"## {item.get('path')} ({item.get('kind')})"] - for entry in item.get("entries") or []: - if not isinstance(entry, dict): - continue - details = [str(detail) for detail in entry.get("details") or []] + for names, kind, details in _grouped(item.get("entries") or []): if len(details) > _ENTRY_DETAILS: details = details[:_ENTRY_DETAILS] + [f"and {len(details) - _ENTRY_DETAILS} more"] - head = f"- {entry.get('name')} ({entry.get('kind')})" + shown = ", ".join(names[:_GROUP_NAMES]) + if len(names) > 1: + more = f" and {len(names) - _GROUP_NAMES} more" if len(names) > _GROUP_NAMES else "" + head = f"- {len(names)} of them ({kind}): {shown}{more}" + else: + head = f"- {shown} ({kind})" lines.append(head + (": " + "; ".join(details) if details else "")) text = "\n".join(lines) if len(text) > _FILE_BUDGET: @@ -284,6 +316,7 @@ def compose_prompt( week_line=week_line(week), page_url=f"{page_url.rstrip('/')}/{week}", target=TARGET_MESSAGES, + words=TARGET_WORDS, ) parts = [guide, _GLOSSARY, _ACT_SYSTEM] if examples: @@ -339,8 +372,31 @@ def feedback_review_prompt(previous: list[str], feedback: str) -> str: ]) +def improve_prompt(prompt: str) -> str: + """The second pass: what is missing and how it reads. The worker puts the draft after it.""" + return "\n\n".join([ + prompt, + "The message above was the writing task, and a draft was written for it. Read the draft below as a player and " + "as the staff member who signs it, and return a better version in the same JSON form:\n" + "- Go through the staff notes, the plugin updates and the config changes one by one. Add every change players " + "would notice that the draft misses, such as a new thing they can do, how something they use now works, or a " + "new stat of a class. Fold small ones into a line that is already there.\n" + "- Say why where the notes, a developer description or an earlier post give the reason and the draft leaves " + "it out. Most big changes should have one short reason.\n" + "- Make every line clear to someone who has not followed the week. A number says what it is, such as a " + "cooldown. Cut settings players never think about and lines that only a few would care about.\n" + "- Rewrite a sentence that only repeats the bullets below it, gives a reason nothing supports, or sounds like " + "a generated list. Vary bullets that all follow one pattern. Match the voice of the earlier posts.\n" + f"- Count the words. When it is over about {TARGET_WORDS}, shorten: cut what few players would miss, such as " + "small extras of a new feature, before anything that changes how people play. " + f"At most {TARGET_MESSAGES} messages.\n" + "- Keep what is already good, and use only what the facts and notes support.", + "Draft:", + ]) + + def review_prompt(prompt: str) -> str: - """Instructions for a second pass. The worker puts the draft after them.""" + """The last pass: is every line right. The worker puts the draft after it.""" return "\n\n".join([ prompt, "The message above was the writing task, and a draft was written for it. Check the draft below now and " @@ -351,11 +407,8 @@ def review_prompt(prompt: str) -> str: "- Compare every `Old --> New` with the earlier posts. The old number is what players were last told or had at " "the start of the week, and the new number is the one at the end of the week. Remove anything already " "announced and any step in between.\n" + "- Check who each effect reaches, and that a stat several classes or items share is not given to one of them.\n" "- Apply every rule again: nothing hidden, nothing staff-only, no chances, roll counts or creature stats.\n" - "- Go through the plugin updates and add any clear change players would notice that the draft missed, " - "such as a new thing they can do or how something they use now works.\n" - "- Rewrite a sentence that only repeats the bullets below it, gives a reason nothing supports, or sounds like " - "a generated list.\n" "- Keep the wording of every line that is already right. Keep the order and the message limits.", "Draft:", ]) @@ -409,12 +462,27 @@ def fit_messages(messages: list[str]) -> list[str]: return fitted -def messages_from_response(payload: dict[str, Any]) -> list[str]: +def pack_messages(messages: list[str]) -> list[str]: + """Join short neighbours, so the post takes as few Discord messages as its text needs.""" + packed: list[str] = [] + for message in messages: + limit = FIRST_LIMIT if len(packed) < 2 else DISCORD_LIMIT - 50 + if packed and len(packed[-1]) + 2 + len(message) <= limit: + packed[-1] += "\n\n" + message + else: + packed.append(message) + return packed + + +def messages_from_response(payload: dict[str, Any], *, pack: bool = False) -> list[str]: + """The post's messages. `pack` joins short ones, which would undo a split staff asked for.""" raw = payload.get("messages") if not isinstance(raw, list): raise FeedbackError("The writer did not return any messages.") cleaned = [clean_message(item) for item in raw if isinstance(item, str)] messages = fit_messages([item for item in cleaned if item]) + if pack: + messages = pack_messages(messages) if not messages: raise FeedbackError("The writer returned an empty post.") if len(messages) > MAX_MESSAGES: diff --git a/backend/src/patchnotes/db.py b/backend/src/patchnotes/db.py index c1a2620e..e6f8c1f7 100644 --- a/backend/src/patchnotes/db.py +++ b/backend/src/patchnotes/db.py @@ -192,6 +192,13 @@ def _local_now(now: datetime | None = None) -> datetime: return moment.astimezone(_zone()) +def friday(week: str, hour: int, minute: int = 0) -> datetime: + """Friday of an ISO week at a local time in PATCHNOTES_TZ.""" + year, number = parse_week(week).split("-W") + day = datetime.fromisocalendar(int(year), int(number), 5) + return day.replace(hour=hour, minute=minute, tzinfo=_zone()) + + def next_week(week: str) -> str: """The ISO week after `week`.""" week_key = parse_week(week) @@ -402,6 +409,7 @@ def migrate() -> None: """ ) cur.execute("ALTER TABLE patchnote_jobs ADD COLUMN IF NOT EXISTS requester TEXT") + cur.execute("ALTER TABLE patchnote_jobs ADD COLUMN IF NOT EXISTS not_before TIMESTAMPTZ") cur.execute("DROP INDEX IF EXISTS patchnote_jobs_active_week_idx") cur.execute( """ @@ -430,6 +438,9 @@ def migrate() -> None: ) """ ) + # Who wrote the post and what to look at, and the version it replaced. + cur.execute("ALTER TABLE patchnote_posts ADD COLUMN IF NOT EXISTS report JSONB") + cur.execute("ALTER TABLE patchnote_posts ADD COLUMN IF NOT EXISTS previous JSONB") cur.execute( """ CREATE TABLE IF NOT EXISTS patchnote_week_meta ( @@ -1147,11 +1158,12 @@ class BulletNotOpen(RuntimeError): _JOB_COLUMNS = ( "id, week, kind, feedback, requester, status, error, changed, line_ids, " - "created_at, claimed_at, finished_at" + "created_at, claimed_at, finished_at, not_before" ) def _expire_jobs(cur) -> None: + """Fail jobs nobody picked up or finished. The Friday post has more time, it is written in three passes.""" cur.execute( """ UPDATE patchnote_jobs @@ -1159,17 +1171,19 @@ def _expire_jobs(cur) -> None: error = CASE WHEN status = 'queued' THEN 'The rewrite agent is not running.' ELSE 'The rewrite took too long.' END - WHERE (status = 'queued' AND created_at < now() - interval '90 seconds' + WHERE (status = 'queued' AND GREATEST(created_at, not_before) < now() - interval '90 seconds' AND NOT EXISTS ( SELECT 1 FROM patchnote_jobs active WHERE active.status = 'running' )) - OR (status = 'running' AND claimed_at < now() - interval '20 minutes') + OR (status = 'running' AND claimed_at < now() - CASE + WHEN requester = 'weekly' AND kind = 'compose' THEN interval '60 minutes' ELSE interval '20 minutes' END) """ ) LINE_JOB_KINDS = ("feedback", "sort") POST_JOB_KINDS = ("compose",) +WEEKLY_REQUESTER = "weekly" def create_job( @@ -1181,6 +1195,15 @@ def create_job( raise ValueError("Invalid job kind") with _connect() as conn, _cursor(conn) as cur: _expire_jobs(cur) + if kind in POST_JOB_KINDS and requester != WEEKLY_REQUESTER: + # Staff do not have to wait for a Friday run that is only waiting for its next try. + cur.execute( + """ + UPDATE patchnote_jobs SET status = 'failed', finished_at = now(), error = 'Staff started it by hand.' + WHERE week = %s AND kind = ANY(%s) AND status = 'queued' AND not_before > now() + """, + (week_key, list(POST_JOB_KINDS)), + ) cur.execute( f""" INSERT INTO patchnote_jobs (week, kind, feedback, requester) @@ -1202,7 +1225,8 @@ def claim_job() -> dict[str, Any] | None: cur.execute( f""" SELECT {_JOB_COLUMNS} FROM patchnote_jobs - WHERE status = 'queued' ORDER BY created_at ASC, id ASC + WHERE status = 'queued' AND (not_before IS NULL OR not_before <= now()) + ORDER BY created_at ASC, id ASC LIMIT 1 FOR UPDATE SKIP LOCKED """ ) @@ -1245,6 +1269,22 @@ def finish_job(job_id: str, *, changed: int | None = None, error: str | None = N return dict(row) +def requeue_job(job_id: str, not_before: datetime) -> dict[str, Any]: + """Put a running job back in the queue for later.""" + with _connect() as conn, _cursor(conn) as cur: + cur.execute( + f""" + UPDATE patchnote_jobs SET status = 'queued', claimed_at = NULL, not_before = %s + WHERE id = %s AND status = 'running' RETURNING {_JOB_COLUMNS} + """, + (not_before, job_id), + ) + row = cur.fetchone() + if row is None: + raise JobNotRunning(job_id) + return dict(row) + + def _read_job(where: str, params: tuple) -> dict[str, Any] | None: with _connect() as conn, _cursor(conn) as cur: _expire_jobs(cur) @@ -1413,33 +1453,61 @@ def get_facts(week: str) -> dict[str, Any] | None: return dict(row) if row else None -def save_post(week: str, messages: list[str], source: str) -> dict[str, Any]: - """Store the week's Discord post as a draft. A rewrite needs approving again.""" +_POST_COLUMNS = "week, messages, source, status, updated_at, report, previous IS NOT NULL AS has_previous" +_POST_VERSION = ( + "jsonb_build_object('messages', patchnote_posts.messages, 'source', patchnote_posts.source, " + "'report', patchnote_posts.report)" +) + + +def save_post( + week: str, messages: list[str], source: str, report: dict[str, Any] | None = None +) -> dict[str, Any]: + """Store the week's Discord post as a draft and keep the version it replaces. + + A rewrite needs approving again. `report` says who wrote it, for staff. + """ if source not in {"writer", "fallback"}: raise ValueError("Invalid post source") with _connect() as conn, _cursor(conn) as cur: cur.execute( - """ - INSERT INTO patchnote_posts (week, messages, source, status) VALUES (%s, %s, %s, 'draft') + f""" + INSERT INTO patchnote_posts (week, messages, source, status, report) VALUES (%s, %s, %s, 'draft', %s) ON CONFLICT (week) DO UPDATE SET messages = EXCLUDED.messages, source = EXCLUDED.source, - status = 'draft', updated_at = now() - RETURNING week, messages, source, status, updated_at + report = EXCLUDED.report, status = 'draft', updated_at = now(), + previous = CASE WHEN patchnote_posts.messages = EXCLUDED.messages + THEN patchnote_posts.previous ELSE {_POST_VERSION} END + RETURNING {_POST_COLUMNS} """, - (parse_week(week), Jsonb(messages), source), + (parse_week(week), Jsonb(messages), source, Jsonb(report) if report else None), ) return dict(cur.fetchone()) -def get_post(week: str) -> dict[str, Any] | None: +def restore_post(week: str) -> dict[str, Any] | None: + """Swap the post with the version it replaced. Doing it again swaps back.""" with _connect() as conn, _cursor(conn) as cur: cur.execute( - "SELECT week, messages, source, status, updated_at FROM patchnote_posts WHERE week = %s", + f""" + UPDATE patchnote_posts SET messages = previous->'messages', source = previous->>'source', + report = NULLIF(previous->'report', 'null'::jsonb), previous = {_POST_VERSION}, + status = 'draft', updated_at = now() + WHERE week = %s AND previous IS NOT NULL + RETURNING {_POST_COLUMNS} + """, (parse_week(week),), ) row = cur.fetchone() return dict(row) if row else None +def get_post(week: str) -> dict[str, Any] | None: + with _connect() as conn, _cursor(conn) as cur: + cur.execute(f"SELECT {_POST_COLUMNS} FROM patchnote_posts WHERE week = %s", (parse_week(week),)) + row = cur.fetchone() + return dict(row) if row else None + + def recent_posts(week: str, limit: int = 4) -> list[list[str]]: """The newest written posts before `week`, newest first, for style and for what players know. diff --git a/backend/src/patchnotes/number_check.py b/backend/src/patchnotes/number_check.py new file mode 100644 index 00000000..52ee5f72 --- /dev/null +++ b/backend/src/patchnotes/number_check.py @@ -0,0 +1,50 @@ +"""Find `Old --> New` numbers in a post that no change of the week shows. + +Standard library only: the rewrite worker runs it on the host. +""" + +from __future__ import annotations + +import re + +_NUMBER = r"-?\d[\d,]*(?:\.\d+)?" +_PAIR = re.compile(rf"(?|;]{{0,24}}?)-->[^\d\n|;-]{{0,12}}?({_NUMBER})") +# The same change in another unit: shares and percentages, ticks, minutes and hours. +_SCALES = (1.0, 100.0, 0.01, 20.0, 0.05, 60.0, 1 / 60, 24.0, 1 / 24) + + +def _value(text: str) -> float: + return float(text.replace(",", "")) + + +def pairs(text: str) -> set[tuple[float, float]]: + return {(_value(old), _value(new)) for old, _, new in _PAIR.findall(text)} + + +def _changes(prompt: str) -> set[tuple[float, float]]: + """The number changes in the staff notes and the facts. The rules and earlier posts before them do not count.""" + starts = [prompt.find(heading) for heading in ("\n\nStaff notes for this week", "\n\nFacts:")] + return pairs(prompt[min([start for start in starts if start >= 0], default=0):]) + + +def _close(first: float, second: float) -> bool: + return abs(first - second) < 1e-6 * max(1.0, abs(second)) + + +def _known(pair: tuple[float, float], changes: set[tuple[float, float]]) -> bool: + return any( + _close(pair[0] * scale, old) and _close(pair[1] * scale, new) + for scale in _SCALES for old, new in changes + ) + + +def unconfirmed(messages: list, prompt: str) -> list[tuple[str, str]]: + """Each line of the post with the number changes on it that the facts and notes do not show.""" + changes = _changes(prompt) + found: list[tuple[str, str]] = [] + for message in messages: + for line in str(message).splitlines(): + missing = [f"{old:g} --> {new:g}" for old, new in sorted(pairs(line)) if not _known((old, new), changes)] + if missing: + found.append((line.strip(), ", ".join(missing))) + return found diff --git a/backend/src/patchnotes/rewrite_worker.py b/backend/src/patchnotes/rewrite_worker.py index 216ed586..d9bd226f 100644 --- a/backend/src/patchnotes/rewrite_worker.py +++ b/backend/src/patchnotes/rewrite_worker.py @@ -20,10 +20,13 @@ import urllib.request from pathlib import Path +from .number_check import unconfirmed from .safety import hidden_words logger = logging.getLogger("patchnotes.rewrite_worker") -_USAGE_LIMIT = re.compile(r"usage[\s_-]*limit|hit.{0,30}limit|quota.{0,30}exceed", re.IGNORECASE) +_USAGE_LIMIT = re.compile( + r"usage[\s_-]*limit|rate[\s_-]*limit|hit.{0,30}limit|limit[\s_-]+reached|quota.{0,30}exceed", re.IGNORECASE +) def _request(api_base: str, staff_key: str, path: str, payload: dict) -> dict: @@ -60,6 +63,9 @@ def _text(value) -> str: # The bot waits 870 seconds for a post (a Discord reply token lasts 15 minutes). _TOTAL_SECONDS = 840.0 _WRITER_SECONDS = 390.0 +# Nobody waits for the Friday run, so it gets the time it needs. The bot waits an hour for it. +_WEEKLY_TOTAL_SECONDS = 2700.0 +_WEEKLY_WRITER_SECONDS = 600.0 _LAST_WRITER_SECONDS = 150.0 _MIN_SECONDS = 30.0 _REVIEW_SECONDS = 120.0 @@ -74,6 +80,11 @@ def _text(value) -> str: because you saw it there.""" +_NUMBERS = """These lines of the draft have number changes that match no change in the facts or staff notes. Each one +is either wrong, or right for a reason such as an earlier post or a value you look up. Confirm it or correct it, and +leave the line out if you cannot:""" + + class WriterError(RuntimeError): """One writer could not produce an output. The message is for the log only.""" @@ -268,20 +279,50 @@ def _attempt(cli: str, model: str, prompt: str, schema: dict, timeout: float, we return output +def _unconfirmed(output: str, prompt: str) -> list[tuple[str, str]]: + """Lines with number changes the prompt does not show. Only a post has messages.""" + try: + return unconfirmed(json.loads(output).get("messages") or [], prompt)[:50] + except Exception: + logger.exception("Could not compare the numbers") + return [] + + +def _improved( + cli: str, model: str, improve: str, draft: str, schema: dict, deadline: float, seconds: float +) -> str | None: + """The same writer's better version of its draft, or None. It leaves time for the check.""" + timeout = min(seconds, deadline - time.monotonic() - 2 * _REVIEW_SECONDS) + if timeout < _REVIEW_SECONDS: + logger.warning("No time left to improve the draft") + return None + try: + output = _attempt(cli, model, f"{improve}\n\n{draft}", schema, timeout) + except Exception as exc: + logger.warning("Improving the draft failed: %s", exc) + return None + logger.info("Writer %s:%s improved its draft", cli, model) + return output + + def _checked( - cli: str, model: str, review: str, draft: str, schema: dict, deadline: float, week: str | None -) -> str: - """The same writer's second look at its draft, with the week's configs when there are any. + cli: str, model: str, review: str, draft: str, schema: dict, deadline: float, week: str | None, + seconds: float = _WRITER_SECONDS, numbers: list[tuple[str, str]] | None = None, +) -> str | None: + """The same writer's last look at its draft, with the week's configs when there are any. - A failed check is tried once more without them. The draft stands if that fails or there is no time. + A failed check is tried once more without them. None if that fails or there is no time. """ + prompt = f"{review}\n\n{draft}" + if numbers: + prompt += "\n\n" + "\n".join([_NUMBERS] + [f"- {found}: {line}" for line, found in numbers]) for lookup_week in (week, None) if week else (None,): - timeout = min(_WRITER_SECONDS, deadline - time.monotonic()) + timeout = min(seconds, deadline - time.monotonic()) if timeout < _REVIEW_SECONDS: logger.warning("No time left to check the draft") break try: - output = _attempt(cli, model, f"{review}\n\n{draft}", schema, timeout, lookup_week) + output = _attempt(cli, model, prompt, schema, timeout, lookup_week) except WriterError as exc: logger.warning("Checking the draft failed: %s", exc) if exc.limit: @@ -292,7 +333,7 @@ def _checked( continue logger.info("Writer %s:%s checked its draft", cli, model) return output - return draft + return None def run_job( @@ -301,29 +342,51 @@ def run_job( review: str | None = None, week: str | None = None, requester: str | None = "weekly", + improve: str | None = None, + may_wait: bool = False, ) -> dict: - """Try each writer in its own empty directory. Returns an output or a short failure.""" - limited = False - deadline = time.monotonic() + _TOTAL_SECONDS + """Try each writer in its own empty directory. Returns an output or a short failure. + + A post is written, improved and checked by the same writer. With `may_wait`, Claude being + out of usage asks for another try later instead of handing the post to the next CLI. + """ + limited = claude_limited = False + weekly = requester == "weekly" and bool(review) # Line jobs of the Friday run have no second look. + seconds = _WEEKLY_WRITER_SECONDS if weekly else _WRITER_SECONDS + deadline = time.monotonic() + (_WEEKLY_TOTAL_SECONDS if weekly else _TOTAL_SECONDS) order = writers(requester) for index, (cli, model) in enumerate(order): + if may_wait and claude_limited and cli != "claude": + logger.warning("Claude is out of usage; asking for another try later") + return {"retry": True} remaining = deadline - time.monotonic() last = index == len(order) - 1 - timeout = min(_WRITER_SECONDS, remaining if last else remaining - _LAST_WRITER_SECONDS) + timeout = min(seconds, remaining if last else remaining - _LAST_WRITER_SECONDS) if timeout < _MIN_SECONDS: logger.warning("No time left for writer %s:%s", cli, model) continue try: output = _attempt(cli, model, prompt, schema, timeout) logger.info("Writer %s:%s finished the job", cli, model) + checks = 0 + if improve: + better = _improved(cli, model, improve, output, schema, deadline, seconds) + output, checks = better or output, checks + bool(better) if review: - output = _checked(cli, model, review, output, schema, deadline, week) + # After staff feedback the facts do not settle a number. + numbers = _unconfirmed(output, prompt) if improve else [] + better = _checked(cli, model, review, output, schema, deadline, week, seconds, numbers) + output, checks = better or output, checks + bool(better) output = _without_hidden(output) if not _usable(output, schema): raise WriterError("only hidden lines were written") - return {"output": output} + return { + "output": output, "writer": f"{cli}:{model}", "checks": checks, + "unconfirmed": _unconfirmed(output, prompt) if improve else [], + } except WriterError as exc: limited = limited or exc.limit + claude_limited = claude_limited or (exc.limit and cli == "claude") logger.warning("Writer %s:%s failed: %s%s", cli, model, exc, " (usage limit)" if exc.limit else "") except Exception: logger.exception("Writer %s:%s failed", cli, model) @@ -338,7 +401,10 @@ def work_once(api_base: str, staff_key: str) -> bool: try: # Staff feedback says what is true, so a rewrite after it needs no lookups. week = None if job.get("feedback") else job.get("week") - result = run_job(claimed["prompt"], claimed["schema"], claimed.get("review"), week, claimed.get("requester")) + result = run_job( + claimed["prompt"], claimed["schema"], claimed.get("review"), week, claimed.get("requester"), + improve=claimed.get("improve"), may_wait=bool(claimed.get("may_wait")), + ) except Exception: logger.exception("Could not process rewrite job") result = _failure("") diff --git a/backend/src/patchnotes/test_compose.py b/backend/src/patchnotes/test_compose.py index f60c9ce4..2137967a 100644 --- a/backend/src/patchnotes/test_compose.py +++ b/backend/src/patchnotes/test_compose.py @@ -118,6 +118,17 @@ def test_developer_descriptions_follow_their_subject(self) -> None: facts = {"plugins": [{"plugin": "p", "old": "1", "new": "2", "commits": ["A", "B"], "details": {"A": "More."}}]} self.assertIn(" - A\n Developer description: More.\n - B", compose.render_facts(facts)) + def test_entries_that_changed_the_same_way_share_a_line(self) -> None: + def entry(name, *details): + return {"name": name, "kind": "changed", "details": list(details)} + + same = [entry(f"Robe {n}", "class: [Mage] --> [Invoker]") for n in range(20)] + text = compose.render_facts({"files": [{"path": "a.yml", "kind": "changed", "entries": [ + *same, entry("Hat", "armor: 1 --> 2"), entry("Mask", "armor: 1 --> 2"), entry("Cape")]}]}) + self.assertIn("- 20 of them (changed): Robe 0, Robe 1,", text) + self.assertIn("Robe 14 and 5 more: class: [Mage] --> [Invoker]", text) + self.assertIn("- Hat (changed): armor: 1 --> 2\n- Mask (changed): armor: 1 --> 2\n- Cape (changed)", text) + def test_feedback_wins_over_the_facts_in_both_passes(self) -> None: prompt = compose.compose_prompt( _FACTS, week="2026-W41", label="5.3", act=None, page_url="x", @@ -131,9 +142,10 @@ def test_feedback_wins_over_the_facts_in_both_passes(self) -> None: self.assertTrue(review.endswith("Draft:")) def test_the_review_carries_the_whole_task(self) -> None: - review = compose.review_prompt("The task and facts") - self.assertTrue(review.startswith("The task and facts")) - self.assertTrue(review.endswith("Draft:")) + for build in (compose.improve_prompt, compose.review_prompt): + review = build("The task and facts") + self.assertTrue(review.startswith("The task and facts")) + self.assertTrue(review.endswith("Draft:")) def test_facts_are_trimmed_to_the_budget(self) -> None: text = compose.render_facts(_FACTS, budget=80) @@ -181,12 +193,22 @@ def test_long_messages_are_split_at_headings(self) -> None: def test_busy_weeks_may_run_past_the_target_but_not_the_cap(self) -> None: prompt = compose.compose_prompt(_FACTS, week="2026-W41", label="5.3", act=None, page_url="x") self.assertIn(f"at most {compose.TARGET_MESSAGES} messages", prompt) + self.assertIn(f"about {compose.TARGET_WORDS} words", prompt) twelve = [f"# Part {n}\n- line" for n in range(12)] self.assertEqual(len(compose.messages_from_response({"messages": twelve})), 12) + self.assertEqual(len(compose.messages_from_response({"messages": twelve}, pack=True)), 1) too_many = [f"# Part {n}\n- line" for n in range(compose.MAX_MESSAGES + 1)] with self.assertRaises(FeedbackError): compose.messages_from_response({"messages": too_many}) + def test_short_messages_are_joined_without_passing_a_limit(self) -> None: + sizes = (1000, 890, 900, 100, 1949, 50) + packed = compose.pack_messages(["x" * size for size in sizes]) + self.assertEqual([len(message) for message in packed], [1892, 1002, 1949, 50]) + self.assertLessEqual(len(packed[0]), compose.FIRST_LIMIT) + self.assertEqual("".join(packed).replace("\n", ""), "x" * sum(sizes)) + self.assertEqual(compose.pack_messages([]), []) + def test_empty_or_missing_posts_fail(self) -> None: with self.assertRaises(FeedbackError): compose.messages_from_response({"messages": [" "]}) diff --git a/backend/src/patchnotes/test_db.py b/backend/src/patchnotes/test_db.py index f4b023fb..76ba7a05 100644 --- a/backend/src/patchnotes/test_db.py +++ b/backend/src/patchnotes/test_db.py @@ -4,7 +4,7 @@ import uuid from contextlib import contextmanager -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from unittest import mock from zoneinfo import ZoneInfo @@ -461,6 +461,53 @@ def test_stale_jobs_expire_and_the_expiry_sticks_when_a_new_job_is_refused(notes assert (row["status"], row["error"]) == ("failed", "The rewrite took too long.") +def test_the_friday_post_may_run_longer_and_wait_for_another_try(notes): + job = db.create_job(WEEK, "compose", requester="weekly") + assert db.claim_job()["id"] == job["id"] + _sql("UPDATE patchnote_jobs SET claimed_at = now() - interval '50 minutes'") + assert db.get_job(job["id"])["status"] == "running" + later = datetime.now(timezone.utc) + timedelta(hours=1) + waiting = db.requeue_job(job["id"], later) + assert (waiting["status"], waiting["not_before"], waiting["claimed_at"]) == ("queued", later, None) + with pytest.raises(db.JobNotRunning): + db.requeue_job(job["id"], later) + _sql("UPDATE patchnote_jobs SET created_at = now() - interval '2 hours'") + assert db.claim_job() is None + assert db.get_job(job["id"])["status"] == "queued" + with pytest.raises(db.JobActive): + db.create_job(WEEK, "compose", requester="weekly") + _sql("UPDATE patchnote_jobs SET not_before = now() - interval '1 minute'") + assert db.claim_job()["id"] == job["id"] + with pytest.raises(db.JobActive): + db.create_job(WEEK, "compose", requester="42") + # Staff can take over a run that only waits. + db.requeue_job(job["id"], later) + assert db.create_job(WEEK, "compose", requester="42")["requester"] == "42" + assert db.get_job(job["id"])["error"] == "Staff started it by hand." + + +def test_friday_is_local(monkeypatch): + monkeypatch.setenv("PATCHNOTES_TZ", "Europe/Berlin") + assert db.friday("2026-W41", 15, 15).astimezone(timezone.utc) == datetime(2026, 10, 9, 13, 15, tzinfo=timezone.utc) + + +def test_a_replaced_post_can_be_swapped_back(notes): + assert db.restore_post(WEEK) is None + report = {"writer": "claude:a", "checks": 2, "unconfirmed": []} + first = db.save_post(WEEK, ["Ours"], "writer", report) + assert (first["report"], first["has_previous"]) == (report, False) + assert db.restore_post(WEEK) is None + db.approve_post(WEEK) + db.save_post(WEEK, ["Test"], "fallback") + # Saving the same text again does not lose the version before it. + assert db.save_post(WEEK, ["Test"], "fallback")["has_previous"] + back = db.restore_post(WEEK) + assert (back["messages"], back["source"], back["report"], back["status"]) == (["Ours"], "writer", report, "draft") + again = db.restore_post(WEEK) + assert (again["messages"], again["source"], again["report"]) == (["Test"], "fallback", None) + assert db.get_post(WEEK)["has_previous"] + + def test_jobs_remember_who_asked(notes): assert db.create_job(WEEK, "sort")["requester"] is None db.create_job(WEEK, "compose", requester="weekly") diff --git a/backend/src/patchnotes/test_number_check.py b/backend/src/patchnotes/test_number_check.py new file mode 100644 index 00000000..96f1c283 --- /dev/null +++ b/backend/src/patchnotes/test_number_check.py @@ -0,0 +1,45 @@ +"""Tests for the numbers of a post against the week's changes.""" + +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +_BACKEND_SRC = Path(__file__).resolve().parents[1] +if str(_BACKEND_SRC) not in sys.path: + sys.path.insert(0, str(_BACKEND_SRC)) + +from patchnotes.number_check import pairs, unconfirmed # noqa: E402 + +_PROMPT = """Write it as `Old --> New`, such as `21 --> 18`. + +["# Update 5.8\\n- Bash 9 --> 7 s"] + +Staff notes for this week, oldest first. + +- Horses 13 --> 16 blocks + +Facts: + +- skills.Challenge.cooldown at level 1: 20 --> 17; alloy: 0.4 --> 0.6; delay: 40 --> 60; price: 1,000 --> 1,500 +""" + + +class NumberCheckTest(unittest.TestCase): + def test_changes_in_the_facts_are_known_in_other_units_too(self) -> None: + post = ["- **Challenge:** cooldown 20 --> 17 s", "- Alloys 40% --> 60%\n- Delay 2 s --> 3 s, 1000 --> **1500** denars, horses 13 --> 16"] + self.assertEqual(unconfirmed(post, _PROMPT), []) + + def test_other_changes_are_listed_with_their_line(self) -> None: + post = ["# Update\n- Challenge 21 --> 18 s\n- Bash 9 --> 7 s, Challenge 20 --> 17 s\n- Two new classes"] + self.assertEqual(unconfirmed(post, _PROMPT), [ + ("- Challenge 21 --> 18 s", "21 --> 18"), ("- Bash 9 --> 7 s, Challenge 20 --> 17 s", "9 --> 7"), + ]) + + def test_pairs_need_a_number_on_both_sides(self) -> None: + self.assertEqual(pairs("none --> 5; 3 --> removed; 0.15 --> 0.2 per second"), {(0.15, 0.2)}) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/src/patchnotes/test_rewrite_worker.py b/backend/src/patchnotes/test_rewrite_worker.py index ee42ae20..bb302732 100644 --- a/backend/src/patchnotes/test_rewrite_worker.py +++ b/backend/src/patchnotes/test_rewrite_worker.py @@ -27,7 +27,7 @@ def _claude_reply(**fields) -> str: class WritersTest(unittest.TestCase): - def _run(self, env, outcomes, review=None, week=None): + def _run(self, env, outcomes, review=None, week=None, **options): calls = [] def run(command, **kwargs): @@ -44,7 +44,7 @@ def run(command, **kwargs): with mock.patch.dict("os.environ", env, clear=True), \ mock.patch("patchnotes.rewrite_worker.subprocess.run", side_effect=run): - result = worker.run_job("Sort", _SCHEMA, review, week) + result = worker.run_job("Sort", _SCHEMA, review, week, **options) return result, calls def test_the_writer_checks_its_own_draft(self) -> None: @@ -55,6 +55,57 @@ def test_the_writer_checks_its_own_draft(self) -> None: self.assertTrue(calls[1][1]["input"].startswith("Check:")) self.assertIn('"draft"', calls[1][1]["input"]) + def test_a_post_is_written_improved_and_then_checked(self) -> None: + replies = [_claude_reply(structured_output={"lines": [text]}) for text in ("draft", "better", "fixed")] + result, calls = self._run(_CLAUDE, replies, "Check:", improve="Improve:") + self.assertEqual(json.loads(result["output"]), {"lines": ["fixed"]}) + self.assertEqual((result["writer"], result["checks"]), ("claude:a", 2)) + self.assertTrue(calls[1][1]["input"].startswith("Improve:")) + self.assertIn('"draft"', calls[1][1]["input"]) + self.assertIn('"better"', calls[2][1]["input"]) + # Nobody waits for the Friday run. A Discord command ends before its reply runs out. + self.assertEqual(calls[0][1]["timeout"], 600) + _, calls = self._run({**_CLAUDE, "PATCHNOTES_CLAUDE_OWNER": "42"}, replies, "Check:", requester="42") + self.assertEqual(calls[0][1]["timeout"], 390) + + def test_a_failed_improvement_keeps_the_draft_for_the_check(self) -> None: + replies = [_claude_reply(structured_output={"lines": ["draft"]}), subprocess.TimeoutExpired("claude", 1), + _claude_reply(structured_output={"lines": ["fixed"]})] + result, calls = self._run(_CLAUDE, replies, "Check:", improve="Improve:") + self.assertEqual((json.loads(result["output"]), result["checks"]), ({"lines": ["fixed"]}, 1)) + self.assertIn('"draft"', calls[2][1]["input"]) + + @mock.patch("patchnotes.rewrite_worker.time.monotonic", side_effect=[0, 0, 0, 2400, 2400, 2400]) + def test_no_improvement_without_time_for_the_check(self, _clock) -> None: + replies = [_claude_reply(structured_output={"lines": [text]}) for text in ("draft", "fixed")] + result, calls = self._run(_CLAUDE, replies, "Check:", improve="Improve:") + self.assertEqual((len(calls), result["checks"]), (2, 1)) + self.assertTrue(calls[1][1]["input"].startswith("Check:")) + + def test_numbers_without_a_change_reach_the_check_and_staff(self) -> None: + schema = {"required": ["messages"], "properties": {"messages": {"type": "array"}}} + draft, fixed = ({"messages": [text]} for text in ("- Bash 9 --> 7 s\n- Dash 5 --> 4 s", "- Dash 5 --> 4 s")) + replies = [_claude_reply(structured_output=value) for value in (draft, draft, fixed)] + with mock.patch(f"{__name__}._SCHEMA", schema): + result, calls = self._run(_CLAUDE, replies, "Check:", improve="Improve:") + self.assertIn("- 9 --> 7: - Bash 9 --> 7 s", calls[2][1]["input"]) + self.assertEqual(result["unconfirmed"], [("- Dash 5 --> 4 s", "5 --> 4")]) + # After staff feedback their numbers stand. + result, calls = self._run(_CLAUDE, replies, "Check:") + self.assertNotIn("match no change", calls[1][1]["input"]) + self.assertEqual(result["unconfirmed"], []) + self.assertEqual(worker._unconfirmed("[]", ""), []) + + def test_the_friday_run_waits_for_claude_before_codex(self) -> None: + limited = subprocess.CompletedProcess([], 1, _claude_reply(is_error=True, result="5-hour limit reached"), "") + broken = subprocess.CompletedProcess([], 1, "", "Please run /login") + result, calls = self._run(_CLAUDE, [limited, limited], may_wait=True) + self.assertEqual((result, len(calls)), ({"retry": True}, 2)) + # Without time left to wait, or when waiting does not help, Codex writes it. + for outcomes, may_wait in (([limited, limited], False), ([broken, broken], True)): + result, calls = self._run(_CLAUDE, [*outcomes, '{"lines":[]}'], may_wait=may_wait) + self.assertEqual((result["writer"], len(calls)), ("codex:c", 3)) + def _run_with_configs(self, outcomes, **patches): env = {**_CLAUDE, "PATCHNOTES_CLAUDE_USER": "tfmc-patchnotes", "PATCHNOTES_CONFIGS_DIR": "/configs"} identity = {"user": 1, "group": 2, "extra_groups": []} @@ -100,7 +151,7 @@ def missing(_name): env = {**_CLAUDE, "PATCHNOTES_CLAUDE_USER": "nobody-here"} with mock.patch.dict("sys.modules", {"pwd": types.SimpleNamespace(getpwnam=missing)}): result, calls = self._run(env, ['{"lines":[]}']) - self.assertEqual(result, {"output": '{"lines":[]}'}) + self.assertEqual(result["output"], '{"lines":[]}') self.assertEqual([call[0][0] for call in calls], ["codex"]) def test_configs_that_cannot_be_prepared_are_skipped(self) -> None: @@ -127,6 +178,7 @@ def test_a_rewrite_after_feedback_reads_no_configs(self, run_job, request) -> No ] worker.work_once("http://api", "key") self.assertEqual(run_job.call_args.args[-2:], (week, None)) + self.assertEqual(run_job.call_args.kwargs, {"improve": None, "may_wait": False}) def test_claude_only_answers_the_friday_run_and_its_owner(self) -> None: env = {**_CLAUDE, "PATCHNOTES_CLAUDE_OWNER": "42"} @@ -179,7 +231,7 @@ def test_a_failed_check_keeps_the_draft(self) -> None: self.assertEqual(json.loads(result["output"]), {"lines": ["draft"]}) self.assertEqual(len(calls), 2) - @mock.patch("patchnotes.rewrite_worker.time.monotonic", side_effect=[0, 0, 0, 800]) + @mock.patch("patchnotes.rewrite_worker.time.monotonic", side_effect=[0, 0, 0, 2650]) def test_no_check_without_enough_time(self, _clock) -> None: _, calls = self._run(_CLAUDE, [_claude_reply(structured_output={"lines": []})], "Check:") self.assertEqual(len(calls), 1) @@ -215,14 +267,14 @@ def test_each_failure_falls_through_to_the_next_writer(self) -> None: for name, failure in failures.items(): with self.subTest(name): result, calls = self._run(_CLAUDE, [failure, failure, '{"lines":[]}']) - self.assertEqual(result, {"output": '{"lines":[]}'}) + self.assertEqual((result["output"], result["writer"]), ('{"lines":[]}', "codex:c")) self.assertEqual([call[0][0] for call in calls], ["claude", "claude", "codex"]) self.assertNotIn("CLAUDE_CODE_OAUTH_TOKEN", calls[2][1]["env"]) self.assertNotIn("STAFF_KEY", calls[2][1]["env"]) def test_without_a_claude_login_codex_runs_first(self) -> None: result, calls = self._run({}, ['{"lines":[]}']) - self.assertEqual(result, {"output": '{"lines":[]}'}) + self.assertEqual(result["output"], '{"lines":[]}') self.assertEqual([call[0][0] for call in calls], ["codex"]) def test_all_writers_out_of_usage_says_so(self) -> None: @@ -244,7 +296,7 @@ def test_unknown_writers_are_ignored(self) -> None: @mock.patch("patchnotes.rewrite_worker.time.monotonic", side_effect=[0, 0, 0, 670, 680, 680]) def test_slow_writers_leave_time_for_the_last_one(self, _clock) -> None: result, calls = self._run(_CLAUDE, [subprocess.TimeoutExpired("claude", 390), '{"lines":[]}']) - self.assertEqual(result, {"output": '{"lines":[]}'}) + self.assertEqual(result["output"], '{"lines":[]}') self.assertEqual([(call[0][0], call[1]["timeout"]) for call in calls], [("claude", 390.0), ("codex", 160.0)]) @@ -285,7 +337,9 @@ def complete(command, **kwargs): self.assertEqual(requests[0].full_url, "http://api/patchnotes/staff/jobs/claim") self.assertEqual(requests[0].get_header("X-staff-key"), "staff-key") self.assertEqual(requests[1].full_url, "http://api/patchnotes/staff/jobs/job-1/result") - self.assertEqual(json.loads(requests[1].data), {"output": '{"lines":[]}'}) + self.assertEqual(json.loads(requests[1].data), { + "output": '{"lines":[]}', "writer": "codex:gpt-6.1-sol", "checks": 0, "unconfirmed": [], + }) self.assertFalse(directories[0].exists()) @mock.patch("patchnotes.rewrite_worker._request") diff --git a/backend/src/patchnotes/test_weekly.py b/backend/src/patchnotes/test_weekly.py index 46192ee5..c57f53e8 100644 --- a/backend/src/patchnotes/test_weekly.py +++ b/backend/src/patchnotes/test_weekly.py @@ -55,6 +55,8 @@ def test_runtime_state_and_submissions_are_ignored(self) -> None: self.assertFalse(weekly.tracked_config("Archaeo/ownership/journals/17948.yml")) self.assertFalse(weekly.tracked_config("CompanionPets/estates/345f77c2-0.yml")) self.assertFalse(weekly.tracked_config("config.yml")) + self.assertFalse(weekly.tracked_config("MMOItems/item/helper_miscellanea.yml")) + self.assertTrue(weekly.tracked_config("MMOItems/item/staff.yml")) def test_hidden_words_never_reach_the_facts(self) -> None: facts = { @@ -115,6 +117,57 @@ def test_new_skills_use_their_player_names(self) -> None: details = weekly.compare(base, current)["files"][0]["entries"][0]["details"] self.assertEqual(details, ["skills.Unbroken: added (level=2)"]) + def test_limited_skill_values_show_what_players_see_at_level_one(self) -> None: + old = """ +display: {name: Templar} +skills: + A: {cooldown: {base: 21.0, per-level: -1, max: 20.0}, heal: {base: 3, per-level: 1}} + B: {cooldown: {base: 12, max: 10}} + C: {duration: {base: 1, min: 2}} +""" + new = old.replace("21.0", "18.0").replace("max: 20.0", "max: 17.0").replace("base: 3,", "base: 4,") + new = new.replace("base: 12", "base: 11").replace("min: 2", "min: 2.5") + new += " D: {level: 3, heal: {base: 9, max: 8}, mana: {base: 5}}\n E: {base: 4, max: 3}\n" + path = "MMOCore/classes/templar.yml" + details = weekly.compare(_snapshot({path: old}), _snapshot({path: new}))["files"][0]["entries"][0]["details"] + self.assertEqual(details, [ + "skills.A.cooldown at level 1: 20 --> 17", + "skills.A.heal.base: 3 --> 4", + "skills.B.cooldown: still 10 at level 1, changed at higher levels", + "skills.C.duration at level 1: 2 --> 2.5", + "skills.D: added (level=3, heal=8, mana=5)", + "skills.E: added (3 at level 1)", + ]) + self.assertIsNone(weekly._level_one({"base": True, "max": 2})) + + def test_only_classes_have_levels_and_menus(self) -> None: + old, new = ("A: {x: 1}\nB:\n speed: {base: %s, max: 5}\n" % base for base in (6, 7)) + new += "C: {options: {slow: 2}, speed: {base: 6, max: 5}}\n" + path = "VehicleFramework/a.yml" + entries = weekly.compare(_snapshot({path: old}), _snapshot({path: new}))["files"][0]["entries"] + self.assertEqual([entry["details"] for entry in entries], [ + ["speed.base: 6 --> 7"], ["options.slow: 2", "speed.base: 6", "speed.max: 5"], + ]) + + def test_a_new_class_shows_its_stats_and_not_its_menus(self) -> None: + slots = "\n".join(f" {n}: {{name: Slot {n}, unlocked-by-default: false}}" for n in range(1, 40)) + new = f"display: {{name: Conjurer}}\nskill-slots:\n{slots}\nexp-table: x\nattributes:\n" \ + " cooldown-reduction: {base: 10}\n speed: {base: 4, max: 3}\n" + facts = weekly.compare(_snapshot({}), _snapshot({"MMOCore/classes/conjurer.yml": new})) + self.assertEqual(facts["files"][0]["entries"][0]["details"], [ + "display.name: Conjurer", "attributes.cooldown-reduction.base: 10", "attributes.speed at level 1: 3", + ]) + + def test_a_new_revision_alone_is_not_a_change(self) -> None: + old = "ROBE:\n base: {name: Robe, armor: 1}\nHAT:\n base: {name: Hat, armor: 1}\n" + new = "ROBE:\n base: {name: Robe, armor: 1, revision-id: 2}\nHAT:\n base: {name: Hat, armor: 2, revision-id: 2}\n" + path = "MMOItems/item/robes.yml" + entries = weekly.compare(_snapshot({path: old}), _snapshot({path: new}))["files"][0]["entries"] + self.assertEqual([(entry["name"], entry["details"]) for entry in entries], [("Hat", ["base.armor: 1 --> 2"])]) + self.assertEqual(weekly.file_entries( + {"display": {"name": "Mage"}, "a": {"revision-id": 1}}, + {"display": {"name": "Mage"}, "a": {"revision-id": 2}}, {}), []) + def test_reformatting_alone_is_not_a_change(self) -> None: base = _snapshot({"Cooking/config.yml": "a: 1\nb: 2\n"}) current = _snapshot({"Cooking/config.yml": "# comment\nb: 2\na: 1\n"}) diff --git a/backend/src/patchnotes/test_weekly_run.py b/backend/src/patchnotes/test_weekly_run.py index 5af2ed27..42eb5ea4 100644 --- a/backend/src/patchnotes/test_weekly_run.py +++ b/backend/src/patchnotes/test_weekly_run.py @@ -118,6 +118,28 @@ def test_details_keep_what_changed_and_drop_reviews_and_hidden_work(self) -> Non self.assertLess(len(long), 1830) self.assertTrue(long.endswith("(shortened)")) + @mock.patch.dict("os.environ", {"PATCHNOTES_HIDDEN_WORDS": "moonpath"}) + def test_work_for_staff_is_left_out_but_staff_weapons_are_not(self) -> None: + for subject in ("Let staff list stowed items", "feat(gui): staff can skip it", "Add an admin menu", + "Staff panel opens faster", "Add a body edit command for staff", "Mage staff-only test weapon", + "Staff can give a Mage Staff into a chest", "Let staff edit weapon damage"): + self.assertEqual(weekly_run.commit_detail(f"{subject}\n\nBody."), "", subject) + commit = {"commits": [{"commit": {"message": subject}}]} + self.assertEqual(weekly_run.commit_subjects("A", "1", "2", lambda _path: commit), [], subject) + for subject in ("fix: Mage Staff now keeps its rune", "feat(magic): staff damage scales with Wisdom", + "Staff of Embers recipe added", "Mages only staff weapons count"): + commit = {"commits": [{"commit": {"message": subject}}]} + self.assertEqual(len(weekly_run.commit_subjects("A", "1", "2", lambda _path: commit)), 1, subject) + kept = "A Mage Staff holds four runes.\n\nOnly the Mage staff is two-handed." + self.assertEqual(weekly_run.commit_detail(f"Mage paths\n\n{kept}"), " ".join(kept.split())) + + def test_facts_of_a_huge_week_still_fit_the_api(self) -> None: + facts = {"files": [{"entries": [{"details": ["x" * 100] * 60}, {"details": ["y"]}]}]} + self.assertEqual(len(weekly_run._fit(facts)["files"][0]["entries"][0]["details"]), 60) + entries = weekly_run._fit(facts, 2000)["files"][0]["entries"] + self.assertEqual(len(entries[0]["details"]), 16) + self.assertEqual((entries[0]["details"][-1], entries[1]["details"]), ("and more changed values", ["y"])) + @mock.patch.dict("os.environ", {}, clear=True) def test_no_details_without_the_hidden_words(self) -> None: self.assertEqual(weekly_run.commit_detail("Subject\n\nBody"), "") diff --git a/backend/src/patchnotes/weekly.py b/backend/src/patchnotes/weekly.py index 1a3f91ea..4e75a20d 100644 --- a/backend/src/patchnotes/weekly.py +++ b/backend/src/patchnotes/weekly.py @@ -25,8 +25,8 @@ from .substance import _canon, _plain, _skip_key, _title MAX_FILE_BYTES = 1_000_000 -MAX_DETAILS = 30 -MAX_ENTRIES = 40 +MAX_DETAILS = 80 +MAX_ENTRIES = 400 _ZIP_ROOTS = ("plugins/", "Minecraft/plugins/") # Runtime state, player submissions and staff tools. Their edits are not news. @@ -42,6 +42,8 @@ "CompanionPets/estates/**", "CoreProtect/**", "Essentials/**", + "MMOCore/classes/test.yml", + "MMOItems/item/helper_*.yml", "LuckPerms/**", "TFMCWeb/**", "VotingPlugin/**", @@ -255,17 +257,67 @@ def _list_change(before: list, after: list) -> str: return "; ".join(parts) or "reordered" -def _brief(node: dict) -> str: +# Bookkeeping that comes with other changes. +_BOOKKEEPING = frozenset({"revision-id"}) +# Menu and levelling parts of a class file, which say nothing about a new class. +_CLASS_MENU = frozenset({ + "skill-slots", "exp-curve", "exp-table", "main-exp-sources", "cast-particle", "options", "key-combos", +}) +_VALUE_KEYS = frozenset({"base", "per-level", "min", "max"}) + + +def _skipped(key: object) -> bool: + return _skip_key(key) or str(key) in _BOOKKEEPING + + +def _level_one(node: Any) -> float | None: + """What a `base`, `per-level`, `min` and `max` value is at level 1, or None for anything else.""" + if not isinstance(node, dict) or "base" not in node or not set(map(str, node)) <= _VALUE_KEYS: + return None + if any(isinstance(value, bool) or not isinstance(value, (int, float)) for value in node.values()): + return None + value = node["base"] + if "max" in node: + value = min(value, node["max"]) + if "min" in node: + value = max(value, node["min"]) + return float(value) + + +def _limited(node: Any) -> bool: + """A value whose `base` is not always what players see, because a limit can cut it.""" + return _level_one(node) is not None and bool({"min", "max"} & set(node)) + + +def _value_change(path: str, before: dict, after: dict) -> str: + old, new = _level_one(before), _level_one(after) + if old == new: + return f"{path}: still {new:g} at level 1, changed at higher levels" + return f"{path} at level 1: {old:g} --> {new:g}" + + +def _brief(node: dict, levels: bool = False) -> str: + if levels and _limited(node): + return f"{_level_one(node):g} at level 1" parts = [] for key, value in node.items(): - if _skip_key(key) or isinstance(value, (dict, list)): + if _skipped(key): continue - parts.append(f"{key}={_fmt(value, 40)}") + first = _level_one(value) if levels else None + if first is not None: + parts.append(f"{key}={first:g}") + elif not isinstance(value, (dict, list)): + parts.append(f"{key}={_fmt(value, 40)}") return ", ".join(parts) or f"{len(node)} keys" -def _leaf_changes(old: Any, new: Any, names: dict[str, str], prefix: str = "") -> list[str]: - """`path: old --> new` for every value that differs, final values only.""" +def _leaf_changes( + old: Any, new: Any, names: dict[str, str], prefix: str = "", *, levels: bool = False +) -> list[str]: + """`path: old --> new` for every value that differs, final values only. + + `levels` is for classes, whose numbers can grow per level up to a limit. + """ out: list[str] = [] def walk(before: Any, after: Any, path: str) -> None: @@ -273,7 +325,7 @@ def walk(before: Any, after: Any, path: str) -> None: return if isinstance(before, dict) and isinstance(after, dict): for key in sorted(set(before) | set(after), key=str): - if _skip_key(key): + if _skipped(key): continue b, a = before.get(key), after.get(key) if _canon(b) == _canon(a): @@ -281,9 +333,11 @@ def walk(before: Any, after: Any, path: str) -> None: label = _segment(key, names) child = f"{path}.{label}" if path else label if b is None and isinstance(a, dict): - out.append(f"{child}: added ({_brief(a)})") + out.append(f"{child}: added ({_brief(a, levels)})") elif a is None and isinstance(b, dict): out.append(f"{child}: removed") + elif levels and _level_one(b) is not None and _level_one(a) is not None and (_limited(b) or _limited(a)): + out.append(_value_change(child, b, a)) else: walk(b, a, child) return @@ -299,16 +353,19 @@ def walk(before: Any, after: Any, path: str) -> None: return out -def _summary(node: Any, names: dict[str, str]) -> list[str]: - """The values of something new, flattened to a few lines.""" +def _summary(node: Any, names: dict[str, str], *, levels: bool = False) -> list[str]: + """The values of something new, flattened to a few lines. `levels` is for classes.""" out: list[str] = [] def walk(value: Any, path: str, depth: int) -> None: if len(out) >= MAX_DETAILS: return + if levels and _limited(value): + out.append(f"{path} at level 1: {_level_one(value):g}") + return if isinstance(value, dict) and depth < 4: for key, item in value.items(): - if _skip_key(key): + if _skipped(key) or (levels and depth == 0 and str(key) in _CLASS_MENU): continue label = _segment(key, names) walk(item, f"{path}.{label}" if path else label, depth + 1) @@ -346,10 +403,11 @@ def file_entries(old: Any, new: Any, names: dict[str, str]) -> list[EntryChange] root = _root_name(new) or _root_name(old) if root: if kind == "added": - return [EntryChange(root, kind, _summary(new, names))] + return [EntryChange(root, kind, _summary(new, names, levels=True))] if kind == "removed": return [EntryChange(root, kind)] - return [EntryChange(root, kind, _leaf_changes(old, new, names))] + details = _leaf_changes(old, new, names, levels=True) + return [EntryChange(root, kind, details)] if details else [] if not isinstance(old, dict) or not isinstance(new, dict): return [EntryChange("file", "changed", [f"value: {_fmt(old)} --> {_fmt(new)}"])] entries: list[EntryChange] = [] @@ -367,7 +425,9 @@ def file_entries(old: Any, new: Any, names: dict[str, str]) -> list[EntryChange] elif after is None: entries.append(EntryChange(name, "removed")) else: - entries.append(EntryChange(name, "changed", _leaf_changes(before, after, names))) + details = _leaf_changes(before, after, names) + if details: + entries.append(EntryChange(name, "changed", details)) else: settings.append(f"{_segment(key, names)}: {_fmt(before)} --> {_fmt(after)}") if settings: diff --git a/backend/src/patchnotes/weekly_run.py b/backend/src/patchnotes/weekly_run.py index adfe0ed5..b5295f26 100644 --- a/backend/src/patchnotes/weekly_run.py +++ b/backend/src/patchnotes/weekly_run.py @@ -43,10 +43,20 @@ _LATE_LIMIT = timedelta(days=3) _MAX_COMMITS = 25 _MAX_DETAIL = 1800 +_MAX_FACTS_BYTES = 1_500_000 # The API refuses 2 MB. _HIDDEN_WORK = re.compile( - r"\b(hidden|secrets?|codex|lore|dungeons?|dev-only|staff|admins?)\b", + r"\b(hidden|secrets?|codex|lore|dungeons?|dev-only|admins?)\b", re.IGNORECASE, ) +# Work for the staff team. A staff is also a weapon, so only the first words always mean the team. +_STAFF_WORK = re.compile( + r"\badmins?\b|\bstaff[ -](?:only|members?|team|commands?|ranks?|permissions?|menus?|panel)\b", re.IGNORECASE +) +_STAFF_MENTION = re.compile( + r"^(?:\w+(?:\([^)]*\))?: )?staff\b|\b(?:lets?|allows?|only|by|for) staff\b|\bstaff (?:can|may|tools?|side|now|lists?)\b", + re.IGNORECASE, +) +_STAFF_WEAPON = re.compile(r"\bmages? staff\b|\bstaff (?:of|weapons?|damage|runes?)\b", re.IGNORECASE) _HIDDEN_SUBJECT = re.compile(r"\b(hidden|secrets?|dev-only)\b|\(dev\)", re.IGNORECASE) _REVIEW_WORK = re.compile( r"^(address|apply|review|fix review|merge|resolve|bump|release|test|tests|ci|docs|refactor|rename|format|keep)\b", @@ -110,9 +120,13 @@ def _github(path: str) -> Any: return json.loads(response.read().decode() or "null") +def _staff_work(text: str) -> bool: + return bool(_STAFF_WORK.search(text) or _STAFF_MENTION.search(_STAFF_WEAPON.sub("weapon", text))) + + def _unsafe_detail(text: str, words: re.Pattern[str]) -> bool: return bool( - words.search(text) or _HIDDEN_WORK.search(text) or _SECRET.search(text) or _EXPLOIT.search(text) + words.search(text) or _HIDDEN_WORK.search(text) or _staff_work(text) or _SECRET.search(text) or _EXPLOIT.search(text) or _PERMISSION.search(text) or _PLACE.search(text) or _XYZ.search(text) or hidden_knowledge_warning(text) ) @@ -166,6 +180,8 @@ def commit_subjects( subject = message.strip().splitlines()[0].strip() if message.strip() else "" if not subject or _MERGE.match(subject) or _HIDDEN_SUBJECT.search(subject): continue + if _staff_work(subject): + continue kind, _ = _split_conventional(subject) if kind in _SKIP_KINDS: continue @@ -179,6 +195,18 @@ def commit_subjects( return [] +def _fit(facts: dict[str, Any], limit: int = _MAX_FACTS_BYTES) -> dict[str, Any]: + """Shorten the entries of an unusually large week, so the API takes the facts.""" + for keep in (40, 15, 5, 1): + if len(json.dumps(facts)) <= limit: + break + for item in facts["files"]: + for entry in item["entries"]: + if len(entry["details"]) > keep: + entry["details"] = entry["details"][:keep] + ["and more changed values"] + return facts + + def build_facts( week: str, base: tuple[datetime, Path], @@ -206,7 +234,7 @@ def build_facts( "partial": partial, } ) - return facts + return _fit(facts) def _api(api_base: str, staff_key: str, method: str, path: str, payload: dict | None = None) -> tuple[int, Any]: diff --git a/discord/patchnotes/README.md b/discord/patchnotes/README.md index 16aa37a6..cc11e349 100644 --- a/discord/patchnotes/README.md +++ b/discord/patchnotes/README.md @@ -11,7 +11,9 @@ this cog shows it to staff and posts it to #updates. 2. The cog posts a staff notice in the review channel, then the post exactly as players will see it, then Approve / Deny / Postpone / Cancel post. It waits up to an hour for the post; without one it falls back to the old line - review. + review. While the writer waits for its usage limit, it waits until 16:15. + The notice says who wrote the post, how often it was checked and which + numbers to look at. 3. Deny asks what should change and rewrites the whole post. 4. Postpone and Cancel post both ask for confirmation and have an undo button. - **Postpone** holds the week: #updates says so at 18:00 and the notes move @@ -33,7 +35,8 @@ this cog shows it to staff and posts it to #updates. | Command | What it does | | --- | --- | | `/patchnotes test-post [week] [here]` | Sends a test copy of the post to the review channel, or this channel with `here`. No buttons, nobody is pinged. | -| `/patchnotes write-post [week]` | Writes the post again from the server changes, dropping earlier feedback. | +| `/patchnotes write-post [week] [rewrite_posted]` | Writes the post again from the server changes, dropping earlier feedback. A week already in #updates needs `rewrite_posted`; the messages there do not change. | +| `/patchnotes undo-write [week]` | Puts back the version the last write or rewrite replaced. Again swaps back. | | `/patchnotes note [week]` | Adds a line for the week's post. The writer treats it as true and puts it in. | | `/patchnotes notes [week]`, `/patchnotes remove-note ` | Lists or removes those lines. | | `/patchnotes act [act] [week]` | Titles an act change week's post with the act, such as `Act 1`. Empty clears it. | diff --git a/discord/patchnotes/format.py b/discord/patchnotes/format.py index 2ae0db94..e54d85bb 100644 --- a/discord/patchnotes/format.py +++ b/discord/patchnotes/format.py @@ -355,6 +355,37 @@ def post_messages(post: dict, mention: str | None = None) -> list[str]: return messages +_WRITER_NAMES = {"opus": "Claude Opus", "sonnet": "Claude Sonnet", "haiku": "Claude Haiku"} + + +def writer_name(writer: str) -> str: + """`claude:claude-opus-5-5` as `Claude Opus`, and `codex:...` as `Codex`.""" + cli, _, model = writer.partition(":") + if cli == "claude": + return next((name for part, name in _WRITER_NAMES.items() if part in model), "Claude") + return cli.capitalize() + + +def writer_lines(post: dict, *, rewritten: bool = False) -> list[str]: + """Who wrote the post, how it was checked and what staff should look at.""" + report = post.get("report") + if not isinstance(report, dict) or not report.get("writer"): + return [] + writer, checks = str(report["writer"]), int(report.get("checks") or 0) + times = {0: "not checked", 1: "checked once"}.get(checks, f"checked {checks} times") + line = f"{'Rewritten' if rewritten else 'Written'} by {writer_name(writer)}, {times}." + if not checks or (not rewritten and not writer.startswith("claude:")): + line += " Please read it more closely than usual." + lines = [line] + doubtful = [item for item in report.get("unconfirmed") or [] if isinstance(item, list) and len(item) == 2] + if doubtful: + lines.append("These numbers match no change in the server files, so check them:") + for text, numbers in doubtful: + short = str(text).lstrip("- ") + lines.append(f"- {numbers} in: {short[:100] + '…' if len(short) > 100 else short}") + return lines + + def post_review_notice( week: str, post: dict, @@ -372,6 +403,7 @@ def post_review_notice( else: lines.append(f"**{title}** for {week_label(week)} is ready to review.") lines.append("Below is exactly what goes to #updates at 18:00, ping included.") + lines += writer_lines(post, rewritten=rewritten) if post.get("source") == "fallback": lines.append( "The writer did not finish, so this is a plain list from the server changes. " @@ -398,11 +430,12 @@ def post_test_notice(week: str, post: dict) -> str: f"Draft for {week_label(week)}, for staff to read before approving.", "Nothing was posted to #updates and nobody was pinged. This copy has no buttons.", ] + lines += writer_lines(post) if post.get("source") == "fallback": lines.append("The writer did not finish, so this is the plain list from the server changes.") if str(post.get("status") or "") == "approved": lines.append("This post is already approved.") - return "\n".join(lines) + return "\n".join(lines)[:DISCORD_LIMIT] def post_test_end() -> str: diff --git a/discord/patchnotes/patchnotes.py b/discord/patchnotes/patchnotes.py index fc76f602..df05335f 100644 --- a/discord/patchnotes/patchnotes.py +++ b/discord/patchnotes/patchnotes.py @@ -40,6 +40,7 @@ review_parts, updates_message, week_label, + writer_lines, ) from .safety import hidden_knowledge_warning from .schedule import ( @@ -66,6 +67,8 @@ _CONFIG_PATH = Path(__file__).resolve().parent / "config.yml" # How long the Friday review waits for the weekly post before using the line review. _POST_WAIT = timedelta(hours=1) +# A writer that is out of usage is tried again until 15:15 and needs up to 45 minutes. +_RETRY_WAIT = timedelta(hours=4, minutes=15) _CANCELLED_REPLY = "This week's post is cancelled. Use Undo cancel to take it back." # Every API call the cog makes is a quick database call, and jobs are polled with separate # requests. A hung API must not hold the week lock (and a staff click) for aiohttp's 5 minutes. @@ -1012,6 +1015,12 @@ async def fetch_post(self, week: str) -> Optional[dict]: def post_ready(post: Optional[dict]) -> bool: return bool(post and post.get("messages")) + @staticmethod + def post_waits_for_usage(post: Optional[dict]) -> bool: + """The writer ran out of usage and is tried again later, or is on that later try now.""" + job = (post or {}).get("job") or {} + return bool(job.get("retry_at")) and job.get("status") in {"queued", "running"} + def ping_mention(self) -> Optional[str]: return f"<@&{self.update_ping_role_id}>" if self.update_ping_role_id else None @@ -1025,7 +1034,10 @@ async def post_due_review(self, week: str, *, ping: bool, now: datetime) -> bool if self.post_ready(post): await self.post_post_review(week, post, ping=ping) return True - if now < friday_at(week, REVIEW_HOUR, self.zone) + _POST_WAIT: + opened = friday_at(week, REVIEW_HOUR, self.zone) + if now < opened + _POST_WAIT: + return False + if self.post_waits_for_usage(post) and now < opened + _RETRY_WAIT: return False logger.warning("No post for %s after an hour; posting the line review", week) await self.post_week_review(week, ping=ping) @@ -1082,6 +1094,17 @@ async def write_post(self, week: str, requester_id: int) -> dict: raise RuntimeError(_api_detail(data, text)) return await self._wait_for_post(week, str(data["job"].get("id") or "")) + async def restore_post(self, week: str) -> dict: + """Put back the version the last write replaced.""" + status, text, data = await self.api_request("POST", f"/patchnotes/staff/weeks/{week}/post/restore") + if status != 200 or not isinstance(data, dict): + raise RuntimeError(_api_detail(data, text)) + return data + + async def is_posted(self, week: str) -> bool: + published = {str(item) for item in await self.config.published_weeks()} + return week in published or bool(dict(await self.config.week_post_messages()).get(week)) + async def _wait_for_post(self, week: str, job_id: str) -> dict: if not job_id: raise RuntimeError("The API did not return a job id.") @@ -2851,20 +2874,55 @@ async def test_post_cmd( name="write-post", description="Write a week's update post again from the server changes, dropping earlier feedback.", ) - @app_commands.describe(week="ISO week, such as 2026-W41. Defaults to the week in review.") + @app_commands.describe( + week="ISO week, such as 2026-W41. Defaults to the week in review.", + rewrite_posted="Also write a week that is already in #updates. The messages there do not change.", + ) @app_commands.check(_has_staff) @app_commands.guild_only() - async def write_post_cmd(self, interaction: discord.Interaction, week: Optional[str] = None): + async def write_post_cmd( + self, interaction: discord.Interaction, week: Optional[str] = None, rewrite_posted: bool = False + ): await interaction.response.defer(ephemeral=True) try: week = await self._command_week(week) + if not rewrite_posted and await self.is_posted(week): + await interaction.followup.send( + f"The post for {week_label(week)} is already in #updates. To write its saved text again anyway, " + "run this with `rewrite_posted: True`.", + ephemeral=True, + ) + return post = await self.write_post(week, interaction.user.id) except Exception as exc: await interaction.followup.send(f"Could not write the post: {exc}"[:300], ephemeral=True) return - await interaction.followup.send( + lines = [ f"Wrote {post_title(post)} with {len(post.get('messages') or [])} messages. " "Use `/patchnotes test-post` to read it. A review that is already posted is not replaced.", + *writer_lines(post), + ] + if post.get("has_previous"): + lines.append("`/patchnotes undo-write` puts the version before it back.") + await interaction.followup.send( + "\n".join(lines)[:2000], ephemeral=True, allowed_mentions=discord.AllowedMentions.none() + ) + + @patchnotes.command(name="undo-write", description="Put back the version of the post the last write replaced.") + @app_commands.describe(week="ISO week, such as 2026-W41. Defaults to the week in review.") + @app_commands.check(_has_staff) + @app_commands.guild_only() + async def undo_write_cmd(self, interaction: discord.Interaction, week: Optional[str] = None): + await interaction.response.defer(ephemeral=True) + try: + week = await self._command_week(week) + post = await self.restore_post(week) + except Exception as exc: + await interaction.followup.send(f"Could not restore the post: {exc}"[:300], ephemeral=True) + return + await interaction.followup.send( + f"Put back the earlier version of {post_title(post)}. Use `/patchnotes test-post` to read it, " + "or run this again to swap back.", ephemeral=True, ) diff --git a/discord/patchnotes/test_cancel.py b/discord/patchnotes/test_cancel.py index cb820dc7..0eb5a499 100644 --- a/discord/patchnotes/test_cancel.py +++ b/discord/patchnotes/test_cancel.py @@ -620,6 +620,72 @@ async def no_poll(): self.assertIn(("WeekCancelConfirmView", "2026-W44"), attached) self.assertIn(("WeekUndoCancelView", WEEK), attached) + async def test_the_review_waits_for_a_writer_that_is_out_of_usage(self) -> None: + cog = _cog({"postponed": False, "deferred_to": None}) + cog.review_channel_id = 5 + lines = [] + + async def post_week_review(week, **_): + lines.append(week) + + cog.post_week_review = post_week_review + waiting = {"messages": [], "job": {"status": "queued", "retry_at": "2026-11-06T12:10:00Z"}} + at_one, at_three, at_five = ( + datetime(2026, 11, 6, hour, 30, tzinfo=timezone.utc) for hour in (12, 14, 16) + ) + for post, now, due in ( + (waiting, at_one, False), (waiting, at_three, False), (waiting, at_five, True), + ({"messages": [], "job": {"status": "running", "retry_at": None}}, at_one, True), (None, at_one, True), + ): + async def fetch_post(_week, found=post): + return found + + cog.fetch_post = fetch_post + lines.clear() + self.assertEqual(await cog.post_due_review(WEEK, ping=False, now=now), due) + self.assertEqual(lines, [WEEK] if due else []) + + async def test_a_posted_week_is_only_written_again_when_asked(self) -> None: + cog = _cog({"postponed": False, "deferred_to": None}, posts={WEEK: [7]}) + written = [] + + async def write_post(week, requester): + written.append((week, requester)) + return {"label": "5.7", "messages": ["a"], "has_previous": True, + "report": {"writer": "codex:x", "checks": 1}} + + cog.write_post = write_post + interaction = _Interaction() + interaction.response = SimpleNamespace(defer=mock.AsyncMock()) + command = pn.PatchNotes.write_post_cmd.callback + await command(cog, interaction, WEEK) + self.assertEqual(written, []) + self.assertIn("already in #updates", interaction.said[-1]) + await command(cog, interaction, WEEK, True) + self.assertEqual(written, [(WEEK, 42)]) + self.assertIn("Written by Codex, checked once.", interaction.said[-1]) + self.assertIn("undo-write", interaction.said[-1]) + cog.config.week_post_messages = _Value({}) + await command(cog, interaction, WEEK) + self.assertEqual(len(written), 2) + + async def test_a_write_can_be_undone(self) -> None: + cog = _cog({"postponed": False, "deferred_to": None}) + answers = [(200, "", {"label": "5.7", "messages": ["a"]}), (404, "", {"detail": "There is no earlier version"})] + calls = [] + + async def api_request(method, path, payload=None): + calls.append((method, path)) + return answers[len(calls) - 1] + + cog.api_request = api_request + interaction = _Interaction() + interaction.response = SimpleNamespace(defer=mock.AsyncMock()) + for expected in ("Put back the earlier version of Update 5.7", "There is no earlier version"): + await pn.PatchNotes.undo_write_cmd.callback(cog, interaction, WEEK) + self.assertIn(expected, interaction.said[-1]) + self.assertEqual(set(calls), {("POST", f"/patchnotes/staff/weeks/{WEEK}/post/restore")}) + async def test_buttons_have_unique_persistent_ids(self) -> None: cog = _cog({"postponed": False, "deferred_to": None}) views = ( diff --git a/discord/patchnotes/test_format.py b/discord/patchnotes/test_format.py index 047e1134..ffe0d205 100644 --- a/discord/patchnotes/test_format.py +++ b/discord/patchnotes/test_format.py @@ -252,6 +252,23 @@ def test_review_notice_explains_a_fallback(self) -> None: self.assertIn("plain list from the server changes", notice) self.assertLessEqual(len(notice), DISCORD_LIMIT) + def test_staff_see_who_wrote_the_post_and_what_to_check(self) -> None: + report = {"writer": "claude:claude-opus-5-5", "checks": 2, + "unconfirmed": [["- **Bless** reaches 3 --> 6 blocks." + "x" * 200, "3 --> 6"]]} + notice = notes_format.post_review_notice("2026-W41", {**self.POST, "report": report}) + self.assertIn("Written by Claude Opus, checked 2 times.\n", notice) + self.assertIn("- 3 --> 6 in: **Bless** reaches", notice) + self.assertLessEqual(len(notice), DISCORD_LIMIT) + codex = {**self.POST, "report": {"writer": "codex:gpt-6.1-sol", "checks": 1}} + self.assertIn("Written by Codex, checked once. Please read it", notes_format.post_test_notice("2026-W41", codex)) + rewritten = notes_format.post_review_notice("2026-W41", codex, rewritten=True) + self.assertIn("Rewritten by Codex, checked once.\n", rewritten) + unchecked = {"report": {"writer": "claude:claude-sonnet-5-5", "checks": 0}} + self.assertEqual(notes_format.writer_lines(unchecked), + ["Written by Claude Sonnet, not checked. Please read it more closely than usual."]) + self.assertEqual(notes_format.writer_lines(self.POST), []) + self.assertEqual(notes_format.writer_name("claude:new"), "Claude") + def test_review_explains_cancel_apart_from_postpone(self) -> None: notice = notes_format.post_review_notice("2026-W41", self.POST) self.assertIn("Postpone holds the whole week until next week", notice) diff --git a/docs/docs/ops/patch-notes-jobs.md b/docs/docs/ops/patch-notes-jobs.md index 9827da5b..1a51a76c 100644 --- a/docs/docs/ops/patch-notes-jobs.md +++ b/docs/docs/ops/patch-notes-jobs.md @@ -25,11 +25,13 @@ The default is `claude:claude-opus-5-5,claude:claude-sonnet-5-5,codex:gpt-6.1-so signed in, out of usage or too slow is skipped, so the post is still written when one subscription ends. The journal names the writer of each job and why earlier ones failed. -After writing the weekly post, the writer gets its draft back once with the facts to correct it. Claude may then also +The weekly post is written in three passes by the same writer: a draft, a better version (what is missing, the reasons, +how it reads) and a check of every line. `number_check.py` gives the check each `Old --> New` that no change in the facts +or notes shows; those still there at the end are listed for staff in the review. In the check Claude may also read Main's gameplay configs from the backup the facts end with. The weekly job keeps them in `/var/lib/private/tfmc-patchnotes-configs/`, so neither the worker nor Codex sees the backups. -`config_pack.py` lists which plugin folders, and leaves out discoveries, lore, player data and logins. If the check -fails or time is short, the draft is used. The facts include the descriptions of the commits behind each plugin update, +`config_pack.py` lists which plugin folders, and leaves out discoveries, lore, player data and logins. If a later pass +fails or time is short, the version before it is used. The Friday run has 45 minutes, a run from Discord 14. The facts include the descriptions of the commits behind each plugin update, without review rounds, hidden features or staff work. - **Claude:** `npm install -g --prefix /usr/local @anthropic-ai/claude-code@` as root, and `/etc/tfmc/patchnotes-claude.env` @@ -39,6 +41,8 @@ without review rounds, hidden features or staff work. - **Who Claude answers:** it runs on one person's own login, so it only writes the Friday post and answers `PATCHNOTES_CLAUDE_OWNER`, that person's Discord id, in the same file. The bot sends the id of whoever pressed Deny or ran a command. Everyone else's rewrites, and those from the website, go to Codex. +- **Out of usage on Friday:** when Claude hits its limit, the post waits and is tried again every hour until 15:15. + After that Codex writes it. Staff can stop waiting with `/patchnotes write-post`. The review says who wrote the post. - **Codex:** root's Codex login. `PATCHNOTES_HIDDEN_WORDS` in `/etc/tfmc/patchnotes.env` is a comma-separated list of names players must not learn, kept From 14c53d6521d66bc0512ecb41b06b2715f14e4c82 Mon Sep 17 00:00:00 2001 From: XxFran10xX <318299142+XxFran10xX@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:38:11 +0100 Subject: [PATCH 2/2] Fix review findings: rebased numbers, level changes, staff wording, size and old APIs Co-Authored-By: Claude Opus 5.5 --- backend/src/api/patchnotes_routes.py | 4 +++- .../src/api/test_patchnotes_post_routes.py | 2 +- backend/src/patchnotes/number_check.py | 24 +++++++++++++++---- backend/src/patchnotes/rewrite_worker.py | 3 ++- backend/src/patchnotes/test_number_check.py | 7 ++++++ backend/src/patchnotes/test_rewrite_worker.py | 6 +++-- backend/src/patchnotes/test_weekly.py | 2 +- backend/src/patchnotes/test_weekly_run.py | 6 +++-- backend/src/patchnotes/weekly.py | 21 ++++++++++------ backend/src/patchnotes/weekly_run.py | 11 +++++---- 10 files changed, 62 insertions(+), 24 deletions(-) diff --git a/backend/src/api/patchnotes_routes.py b/backend/src/api/patchnotes_routes.py index 32a1945b..74fe305f 100644 --- a/backend/src/api/patchnotes_routes.py +++ b/backend/src/api/patchnotes_routes.py @@ -20,6 +20,7 @@ from src.api.map_access import require_site_staff from src.patchnotes.compose import ( POST_SCHEMA, + clean_message, compose_prompt, feedback_review_prompt, review_prompt, @@ -1144,7 +1145,8 @@ def _post_report(body: JobResultBody, messages: list[str]) -> dict[str, Any] | N if not body.writer: return None text = "\n".join(messages) - lines = [[line, numbers] for line, numbers in body.unconfirmed if line.strip() and line in text] + cleaned = [[clean_message(line), numbers] for line, numbers in body.unconfirmed] + lines = [item for item in cleaned if item[0] and item[0] in text] return {"writer": body.writer, "checks": body.checks, "unconfirmed": lines[:_MAX_UNCONFIRMED]} diff --git a/backend/src/api/test_patchnotes_post_routes.py b/backend/src/api/test_patchnotes_post_routes.py index b64e0318..e90f36d2 100644 --- a/backend/src/api/test_patchnotes_post_routes.py +++ b/backend/src/api/test_patchnotes_post_routes.py @@ -257,7 +257,7 @@ def test_writer_result_is_stored_as_a_draft(self) -> None: def test_staff_learn_who_wrote_it_and_which_numbers_to_check(self) -> None: messages = ["# Update 5.3", "- Bash 9 --> 7 s"] body = {"output": json.dumps({"messages": messages}), "writer": "claude:claude-opus-5-5", "checks": 2, - "unconfirmed": [["- Bash 9 --> 7 s", "9 --> 7"], ["- Removed 2 --> 1 s", "2 --> 1"]]} + "unconfirmed": [["- Bash 9 --> 7 s \u2694\ufe0f", "9 --> 7"], ["- Removed 2 --> 1 s", "2 --> 1"]]} report = {"writer": "claude:claude-opus-5-5", "checks": 2, "unconfirmed": [["- Bash 9 --> 7 s", "9 --> 7"]]} url = "/patchnotes/staff/jobs/22222222-2222-2222-2222-222222222222/result" # A rewrite after feedback keeps the messages as staff asked for them. diff --git a/backend/src/patchnotes/number_check.py b/backend/src/patchnotes/number_check.py index 52ee5f72..a975afcf 100644 --- a/backend/src/patchnotes/number_check.py +++ b/backend/src/patchnotes/number_check.py @@ -27,24 +27,38 @@ def _changes(prompt: str) -> set[tuple[float, float]]: return pairs(prompt[min([start for start in starts if start >= 0], default=0):]) +def _earlier(prompt: str) -> set[tuple[float, float]]: + """The number changes earlier posts announced. Each post is a JSON list on its own line.""" + return pairs("\n".join( + line.replace("\\n", "\n") for line in prompt.split("\n\nFacts:")[0].splitlines() if line.startswith('["') + )) + + def _close(first: float, second: float) -> bool: return abs(first - second) < 1e-6 * max(1.0, abs(second)) -def _known(pair: tuple[float, float], changes: set[tuple[float, float]]) -> bool: - return any( +def _known( + pair: tuple[float, float], changes: set[tuple[float, float]], earlier: set[tuple[float, float]] +) -> bool: + if any( _close(pair[0] * scale, old) and _close(pair[1] * scale, new) for scale in _SCALES for old, new in changes - ) + ): + return True + # An earlier post said 18 --> 15 and the facts say 18 --> 11, so players read 15 --> 11. + return any(new == pair[0] and (old, pair[1]) in changes for old, new in earlier) def unconfirmed(messages: list, prompt: str) -> list[tuple[str, str]]: """Each line of the post with the number changes on it that the facts and notes do not show.""" - changes = _changes(prompt) + changes, earlier = _changes(prompt), _earlier(prompt) found: list[tuple[str, str]] = [] for message in messages: for line in str(message).splitlines(): - missing = [f"{old:g} --> {new:g}" for old, new in sorted(pairs(line)) if not _known((old, new), changes)] + missing = [ + f"{old:g} --> {new:g}" for old, new in sorted(pairs(line)) if not _known((old, new), changes, earlier) + ] if missing: found.append((line.strip(), ", ".join(missing))) return found diff --git a/backend/src/patchnotes/rewrite_worker.py b/backend/src/patchnotes/rewrite_worker.py index d9bd226f..40abe4fd 100644 --- a/backend/src/patchnotes/rewrite_worker.py +++ b/backend/src/patchnotes/rewrite_worker.py @@ -351,7 +351,8 @@ def run_job( out of usage asks for another try later instead of handing the post to the next CLI. """ limited = claude_limited = False - weekly = requester == "weekly" and bool(review) # Line jobs of the Friday run have no second look. + # Line jobs have no `improve`, and neither has an older API, which ends every job after 20 minutes. + weekly = requester == "weekly" and bool(improve) seconds = _WEEKLY_WRITER_SECONDS if weekly else _WRITER_SECONDS deadline = time.monotonic() + (_WEEKLY_TOTAL_SECONDS if weekly else _TOTAL_SECONDS) order = writers(requester) diff --git a/backend/src/patchnotes/test_number_check.py b/backend/src/patchnotes/test_number_check.py index 96f1c283..c18e6f84 100644 --- a/backend/src/patchnotes/test_number_check.py +++ b/backend/src/patchnotes/test_number_check.py @@ -37,6 +37,13 @@ def test_other_changes_are_listed_with_their_line(self) -> None: ("- Challenge 21 --> 18 s", "21 --> 18"), ("- Bash 9 --> 7 s, Challenge 20 --> 17 s", "9 --> 7"), ]) + def test_a_change_an_earlier_post_started_goes_on_from_there(self) -> None: + prompt = 'Rules\n\n["- Bash 18 --> 15 s\\\\n- Dash 9 --> 7 s"]\n\nFacts:\n\n- cooldown: 18 --> 11; x: 5 --> 4' + self.assertEqual(unconfirmed(["- Bash 15 --> 11 s"], prompt), []) + # Only the same change counts, and one that is only in an earlier post does not. + self.assertEqual([found for _, found in unconfirmed(["- 15 --> 4\n- 7 --> 11\n- 9 --> 7"], prompt)], + ["15 --> 4", "7 --> 11", "9 --> 7"]) + def test_pairs_need_a_number_on_both_sides(self) -> None: self.assertEqual(pairs("none --> 5; 3 --> removed; 0.15 --> 0.2 per second"), {(0.15, 0.2)}) diff --git a/backend/src/patchnotes/test_rewrite_worker.py b/backend/src/patchnotes/test_rewrite_worker.py index bb302732..c068bbba 100644 --- a/backend/src/patchnotes/test_rewrite_worker.py +++ b/backend/src/patchnotes/test_rewrite_worker.py @@ -63,8 +63,10 @@ def test_a_post_is_written_improved_and_then_checked(self) -> None: self.assertTrue(calls[1][1]["input"].startswith("Improve:")) self.assertIn('"draft"', calls[1][1]["input"]) self.assertIn('"better"', calls[2][1]["input"]) - # Nobody waits for the Friday run. A Discord command ends before its reply runs out. + # Nobody waits for the Friday run, but an older API does. A Discord command ends before its reply runs out. self.assertEqual(calls[0][1]["timeout"], 600) + _, calls = self._run(_CLAUDE, replies, "Check:") + self.assertEqual(calls[0][1]["timeout"], 390) _, calls = self._run({**_CLAUDE, "PATCHNOTES_CLAUDE_OWNER": "42"}, replies, "Check:", requester="42") self.assertEqual(calls[0][1]["timeout"], 390) @@ -231,7 +233,7 @@ def test_a_failed_check_keeps_the_draft(self) -> None: self.assertEqual(json.loads(result["output"]), {"lines": ["draft"]}) self.assertEqual(len(calls), 2) - @mock.patch("patchnotes.rewrite_worker.time.monotonic", side_effect=[0, 0, 0, 2650]) + @mock.patch("patchnotes.rewrite_worker.time.monotonic", side_effect=[0, 0, 0, 800]) def test_no_check_without_enough_time(self, _clock) -> None: _, calls = self._run(_CLAUDE, [_claude_reply(structured_output={"lines": []})], "Check:") self.assertEqual(len(calls), 1) diff --git a/backend/src/patchnotes/test_weekly.py b/backend/src/patchnotes/test_weekly.py index c57f53e8..efb4ddf7 100644 --- a/backend/src/patchnotes/test_weekly.py +++ b/backend/src/patchnotes/test_weekly.py @@ -122,7 +122,7 @@ def test_limited_skill_values_show_what_players_see_at_level_one(self) -> None: display: {name: Templar} skills: A: {cooldown: {base: 21.0, per-level: -1, max: 20.0}, heal: {base: 3, per-level: 1}} - B: {cooldown: {base: 12, max: 10}} + B: {cooldown: {base: 12, per-level: -1, max: 10}, range: {base: 12, max: 10}} C: {duration: {base: 1, min: 2}} """ new = old.replace("21.0", "18.0").replace("max: 20.0", "max: 17.0").replace("base: 3,", "base: 4,") diff --git a/backend/src/patchnotes/test_weekly_run.py b/backend/src/patchnotes/test_weekly_run.py index 42eb5ea4..cc685786 100644 --- a/backend/src/patchnotes/test_weekly_run.py +++ b/backend/src/patchnotes/test_weekly_run.py @@ -121,12 +121,12 @@ def test_details_keep_what_changed_and_drop_reviews_and_hidden_work(self) -> Non @mock.patch.dict("os.environ", {"PATCHNOTES_HIDDEN_WORDS": "moonpath"}) def test_work_for_staff_is_left_out_but_staff_weapons_are_not(self) -> None: for subject in ("Let staff list stowed items", "feat(gui): staff can skip it", "Add an admin menu", - "Staff panel opens faster", "Add a body edit command for staff", "Mage staff-only test weapon", + "Staff panel opens faster", "Add a body edit command for staff", "Staff chat lasts a week", "Mage staff-only test weapon", "Staff can give a Mage Staff into a chest", "Let staff edit weapon damage"): self.assertEqual(weekly_run.commit_detail(f"{subject}\n\nBody."), "", subject) commit = {"commits": [{"commit": {"message": subject}}]} self.assertEqual(weekly_run.commit_subjects("A", "1", "2", lambda _path: commit), [], subject) - for subject in ("fix: Mage Staff now keeps its rune", "feat(magic): staff damage scales with Wisdom", + for subject in ("fix: Staff cooldown reduced", "fix: Mage Staff now keeps its rune", "feat(magic): staff damage scales with Wisdom", "Staff of Embers recipe added", "Mages only staff weapons count"): commit = {"commits": [{"commit": {"message": subject}}]} self.assertEqual(len(weekly_run.commit_subjects("A", "1", "2", lambda _path: commit)), 1, subject) @@ -139,6 +139,8 @@ def test_facts_of_a_huge_week_still_fit_the_api(self) -> None: entries = weekly_run._fit(facts, 2000)["files"][0]["entries"] self.assertEqual(len(entries[0]["details"]), 16) self.assertEqual((entries[0]["details"][-1], entries[1]["details"]), ("and more changed values", ["y"])) + long = {"files": [{"entries": [{"details": ["x" * 5000]}]}]} + self.assertEqual(weekly_run._fit(long, 2000)["files"][0]["entries"][0]["details"], ["x" * 120]) @mock.patch.dict("os.environ", {}, clear=True) def test_no_details_without_the_hidden_words(self) -> None: diff --git a/backend/src/patchnotes/weekly.py b/backend/src/patchnotes/weekly.py index 4e75a20d..86c5e2c4 100644 --- a/backend/src/patchnotes/weekly.py +++ b/backend/src/patchnotes/weekly.py @@ -263,6 +263,7 @@ def _list_change(before: list, after: list) -> str: _CLASS_MENU = frozenset({ "skill-slots", "exp-curve", "exp-table", "main-exp-sources", "cast-particle", "options", "key-combos", }) +_TOP_LEVEL = 30 # Past the last act's class cap. _VALUE_KEYS = frozenset({"base", "per-level", "min", "max"}) @@ -276,7 +277,11 @@ def _level_one(node: Any) -> float | None: return None if any(isinstance(value, bool) or not isinstance(value, (int, float)) for value in node.values()): return None - value = node["base"] + return _at_level(node, 1) + + +def _at_level(node: dict, level: int) -> float: + value = node["base"] + node.get("per-level", 0) * (level - 1) if "max" in node: value = min(value, node["max"]) if "min" in node: @@ -289,11 +294,13 @@ def _limited(node: Any) -> bool: return _level_one(node) is not None and bool({"min", "max"} & set(node)) -def _value_change(path: str, before: dict, after: dict) -> str: - old, new = _level_one(before), _level_one(after) - if old == new: - return f"{path}: still {new:g} at level 1, changed at higher levels" - return f"{path} at level 1: {old:g} --> {new:g}" +def _value_change(path: str, before: dict, after: dict) -> list[str]: + old, new = _at_level(before, 1), _at_level(after, 1) + if old != new: + return [f"{path} at level 1: {old:g} --> {new:g}"] + if any(_at_level(before, level) != _at_level(after, level) for level in range(2, _TOP_LEVEL + 1)): + return [f"{path}: still {new:g} at level 1, changed at higher levels"] + return [] def _brief(node: dict, levels: bool = False) -> str: @@ -337,7 +344,7 @@ def walk(before: Any, after: Any, path: str) -> None: elif a is None and isinstance(b, dict): out.append(f"{child}: removed") elif levels and _level_one(b) is not None and _level_one(a) is not None and (_limited(b) or _limited(a)): - out.append(_value_change(child, b, a)) + out.extend(_value_change(child, b, a)) else: walk(b, a, child) return diff --git a/backend/src/patchnotes/weekly_run.py b/backend/src/patchnotes/weekly_run.py index b5295f26..a8b6430a 100644 --- a/backend/src/patchnotes/weekly_run.py +++ b/backend/src/patchnotes/weekly_run.py @@ -50,11 +50,10 @@ ) # Work for the staff team. A staff is also a weapon, so only the first words always mean the team. _STAFF_WORK = re.compile( - r"\badmins?\b|\bstaff[ -](?:only|members?|team|commands?|ranks?|permissions?|menus?|panel)\b", re.IGNORECASE + r"\badmins?\b|\bstaff[ -](?:only|members?|team|chat|commands?|ranks?|permissions?|menus?|panel)\b", re.IGNORECASE ) _STAFF_MENTION = re.compile( - r"^(?:\w+(?:\([^)]*\))?: )?staff\b|\b(?:lets?|allows?|only|by|for) staff\b|\bstaff (?:can|may|tools?|side|now|lists?)\b", - re.IGNORECASE, + r"\b(?:lets?|allows?|only|by|for) staff\b|\bstaff (?:can|may|tools?|side|now|lists?)\b", re.IGNORECASE ) _STAFF_WEAPON = re.compile(r"\bmages? staff\b|\bstaff (?:of|weapons?|damage|runes?)\b", re.IGNORECASE) _HIDDEN_SUBJECT = re.compile(r"\b(hidden|secrets?|dev-only)\b|\(dev\)", re.IGNORECASE) @@ -196,7 +195,7 @@ def commit_subjects( def _fit(facts: dict[str, Any], limit: int = _MAX_FACTS_BYTES) -> dict[str, Any]: - """Shorten the entries of an unusually large week, so the API takes the facts.""" + """Shorten the entries of an unusually large week, then their text, so the API takes the facts.""" for keep in (40, 15, 5, 1): if len(json.dumps(facts)) <= limit: break @@ -204,6 +203,10 @@ def _fit(facts: dict[str, Any], limit: int = _MAX_FACTS_BYTES) -> dict[str, Any] for entry in item["entries"]: if len(entry["details"]) > keep: entry["details"] = entry["details"][:keep] + ["and more changed values"] + if len(json.dumps(facts)) > limit: + for item in facts["files"]: + for entry in item["entries"]: + entry["details"] = [detail[:120] for detail in entry["details"]] return facts