Skip to content

Split commands.py, add Ruff, Mypy and a lint CI job - #10

Merged
joaquinmuzzi merged 12 commits into
masterfrom
claude/project-thread-mcnkpn
Oct 19, 2026
Merged

joaquinmuzzi merged 12 commits into
masterfrom
claude/project-thread-mcnkpn

Conversation

@joaquinmuzzi

Copy link
Copy Markdown
Owner

Before: src/controller/commands.py was a single 2,069-line file. It mixed the slash commands, the profile calculation, ICC kill resolution, embeds and caching. The repo had no linter, no type checker and no pyproject.toml, and CI only ran pytest.

After: every command has its own module in src/controller/commands/. The logic shared with the cron lives in src/services/, and no new file is longer than 347 lines. Ruff and Mypy are configured in pyproject.toml and both pass cleanly, with 0 Mypy errors. CI gets a lint job next to pytest. A multi-stage Dockerfile in docker/ runs the bot outside Railway.

This is a pure refactor. Command names, embed texts and behavior stay the same. The one exception is a real bug found by Ruff (RUF006): the background task that records characters for the cron could be garbage-collected before it finished. It now has a regression test.

How: one small commit per step.

  1. Move the business logic to src/services/.
  2. Split the commands into modules, one per command.
  3. Add pyproject.toml.
  4. Run ruff format in its own commit, listed in .git-blame-ignore-revs.
  5. Apply the ruff check fixes.
  6. Fix the tracking bug.
  7. Fix the Mypy errors.
  8. Extend CI, add the Dockerfile and update the README.

Tests now patch names in the module that uses them, instead of relying on re-exports. tools/ imports from src/services/.

Verified locally:

  • pytest: 136 passed before, 137 passed after.
  • A 48-scenario differential harness (/ping, /p, /dps, /logs, /ptoc, /ia, with cache, stale and error paths) gives byte-identical output to bfad308.
  • The slash command tree is the same.
  • main.py boots up to bot.run with the same 7 commands.
  • nixpacks plan gives the same plan (start bash ./run_railway.sh).
  • pyproject.toml has no [project] table, and the Dockerfile sits in docker/. Both choices keep Railway building with Nixpacks.

Not tested: real Discord, Warmane or UwU Logs traffic.

Known and left untouched, because fixing it changes behavior: inferred from the code, not seen in Discord, /dps served from cache renders without the boss separators.


Generated by Claude Code

joaquinmuzzi and others added 12 commits October 19, 2026 18:21
commands.py mixed the Discord handlers with the logic that builds a
/personaje profile, resolves the ICC kills and names the cache keys, and
tools/preload_personaje_cache.py had to import that logic from the
Discord layer. The logic now lives in src/services/, with no Discord
imports, so the bot and the cron share it from a neutral place:

- cache_keys.py: external cache keys.
- character_input.py: name and realm validation.
- spec_gearscore.py: specs of a character and the last GS of each one.
- icc_kills.py: Marrowgar/Deathwhisper kills from UwU Logs, Storming
  the Citadel, equipped items and kills already confirmed.
- profile.py: the /personaje payload (_compute_personaje_base,
  serialization and the checks before caching it).
- tracking.py: _track_character, fire-and-forget to Postgres.

Pure move: the function bodies are unchanged. The only edit is in
_fetch_item_source_hint, whose import of SESSION and HTTP_TIMEOUT
moves from inside the function to the top of the module (the constants
module was already imported). The loggers keep the name
"gschecker.commands", so the Railway log lines stay the same.

The cron and the tests now import from src.services, and the tests
patch _fetch_guild_rank and async_track_character_lookup where they are
looked up now (src.services.profile, src.services.tracking).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
src/controller/commands.py had grown to 2,000 lines, with seven slash
commands inside one register_commands function. It is now a package:

- personaje.py: /personaje and /p, with the final-edit check.
- dps.py, logs.py, ptoc.py, ia.py, ping.py: one command each.
- interactions.py: the helpers every command uses to defer, edit and
  report errors on a discord.Interaction, and the usage log line.

Each module exposes register(bot) and register_commands in __init__.py
calls them in the same order as before, so main.py does not change and
the command tree sent to Discord is identical (names, descriptions,
parameters and order, compared with to_dict()). The command bodies are
copied unchanged; an AST comparison against the old file shows every
function identical except register_commands itself.

Tests now patch the fetchers where each command looks them up. The
patched_fetchers fixture puts one mock per fetcher in every module that
uses it, as the single commands.py patch did before, so /dps and /ia
tests keep sharing the /p mocks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
After the split, personaje.py was still 460 lines and dps.py built the
same embed twice (once live, once from the cache). This keeps every
command module under 400 lines without changing what the bot sends:

- personaje.py picks where the profile comes from (cache, stale copy
  while the armory circuit is open, or live) and personaje_live.py
  builds it live: armory, loading animation while UwU Logs answers,
  cache write and the final-edit check. _personaje_impl is now short
  steps (_send_cached_profile, _send_stale_profile, _send_live_profile,
  _wait_for_uwu_kills, _cache_final_profile) instead of 300 lines.
- dps.py builds its embed in one place (_build_dps_embed) for both the
  live and the cached path. The live path still groups the rows in
  place and the cached one on copies, as before, so the cached payload
  is the same.
- _reply_command_error replaces the five copies of the except chain
  (NotFound, expired token, network error, ValueError, anything else).
  /p still logs unexpected errors with logger.exception.
- ia.py moves the embed to _build_ia_embed and imports os and
  get_character_stats at the top instead of inside the command.

Checked with a differential run of 48 scenarios (every command, cache
hits, stale copies, the circuit breaker, UwU Logs failures and every
error branch) against bfad308: the messages, embeds, views and calls
to the armory, UwU Logs and Postgres mocks are byte-identical.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
The repo had no linter or type checker. pyproject.toml now configures:

- Ruff 0.17 (the same rule set as joaquinmuzzi/Tonos): pycodestyle
  errors, pyflakes, isort, bugbear, pyupgrade, simplify, pytest style
  and Ruff's own rules, with a 110-column line and Python 3.11 as the
  target (the version Railway runs, from .tool-versions). Spanish text
  keeps its en dashes, minus and multiplication signs, and tools/ may
  import after adding the repo root to sys.path.
- Mypy without strict mode: check_untyped_defs so it reads the body of
  every function, plus strict_equality and the warn_* flags. Strict mode
  can come later, module by module.
- pytest: the same options pytest.ini had, so pytest.ini goes away.

There is no [project] table on purpose: the bot is not an installable
package and Nixpacks installs it from requirements.txt. `nixpacks plan`
gives the same build plan as before (Python 3.11, pip install -r
requirements.txt, start with bash ./run_railway.sh from the Procfile).

The tools are pinned in requirements-dev.txt, which CI already
installs. .gitattributes keeps .py and .sh files in LF even on a
Windows checkout with core.autocrlf.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
Only formatting, from `ruff format .` with the pyproject.toml config: no
code changes, so this commit can be skipped in git blame (it is listed
in .git-blame-ignore-revs in the next commit).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
ruff check --fix took care of most of it: import order, unused imports
and noqa comments, `asyncio.TimeoutError` (an alias of TimeoutError
since Python 3.11), redundant open() modes, quoted annotations, nested
`with` blocks and an f-string without placeholders. By hand:

- Unused variables: three leftovers in warmane.py are removed, and the
  unpacked values nobody reads get a leading underscore.
- Nested ifs and if/else blocks become one condition or a ternary, and
  list concatenations become unpacking.
- AuditSeverity stays (str, Enum) with a noqa for UP042: StrEnum would
  change what str() returns for its members.
- Tests: the shared fixtures (bot, patched_fetchers) move to
  conftest.py and the shared data to tests/helpers.py. Importing
  fixtures from test_personaje.py needed `noqa: F811` on every test,
  and ruff format had moved those comments to the wrong lines. Also
  split composite asserts, tuple parametrize names, match= on
  pytest.raises and no underscore on injected mock arguments.

No behavior change: the 136 tests pass and the 48-scenario comparison
against bfad308 is still byte-identical. The remaining finding
(RUF006 in tracking.py) is a real issue and gets its own commit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
_track_character started the Postgres write with loop.create_task() and
dropped the task. The event loop keeps only weak references to tasks,
so the garbage collector may destroy one before it finishes (the
asyncio docs warn about this for create_task). Ruff flags it as
RUF006. A dropped write is silent: the character just never reaches
tracked_characters and the cron does not preload it.

The pending tasks now live in a module-level set until they finish.
The test checks that the task is kept while the insert waits and
released once it is done.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
Mypy reported 34 errors with the new config. All of them are fixed with
annotations, renames or None checks; none changes what the bot does:

- Empty dict/list literals that later hold mixed values get an explicit
  type (uwu.py, warmane.py, seed_names.py, a few tests).
- Variables reused for two different things get two names (talents from
  the API in profile_scraper.py, gem ids in auditor.py, the name set in
  preload_character_gs.py).
- get_gear_data checks for a missing .item-model with an if instead of
  catching the AttributeError of calling .find_all on None. Same log line
  and same empty result.
- _compute_personaje_base reads summary["name"]: both callers (/p and the
  cron) always pass it, so the old .get() could never return None.
- bis_guides exposed cache_clear by sticking an attribute on a plain
  function, which mypy cannot type. It is now clear_realm_cache().
- coach.py splits the model lookup in two lines so mypy sees a str.
- Tests assert the value is not None before using it.

The 48-scenario differential harness still gives byte-identical output
against bfad308.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
The existing tests workflow only ran pytest. It now has a second job,
lint, that runs ruff check, ruff format --check and mypy with the same
Python and requirements-dev.txt as the tests, so style and type errors
show up in the PR instead of in review.

It extends tests.yml instead of adding a new workflow. Railway waits
for every check suite on the commit before deploying (checkSuites in
.railway/railway.py), so a lint failure now also holds the deploy, the
same as a failing test.

Also:
- permissions: contents read, the only thing both jobs need.
- concurrency cancels an older run only on pull requests. On master
  every commit keeps its run, because Railway waits on each one.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
Railway keeps building with Nixpacks; this image is for running the bot
locally or on another host with the same Python as production.

- build stage: installs requirements.txt into a venv.
- runtime stage: copies only that venv and the code, runs as a non-root
  user (uid 10001) that owns /app, because main.py creates logs/ and the
  scraper rewrites the JSON caches in static/.
- python:3.11.11-slim, the version in .tool-versions.
- The same image runs the cron with
  `python -m tools.run_scheduled_preload` as the command.

It lives in docker/ and not at the repo root, so Railway cannot pick it
up instead of Nixpacks. Its ignore file is docker/Dockerfile.dockerignore,
which BuildKit reads for `-f docker/Dockerfile`; no root .dockerignore.
`nixpacks plan` gives the same plan as before.

Tested here by building the image (with the sandbox's TLS CA injected
only for the test build) and running main.py inside it up to bot.run:
it registers the same 7 slash commands as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
The README still described src/controller/commands.py as one file that
held the slash commands and the profile logic. It now shows:

- the commands package, one module per command, and src/services with
  the logic shared with the cron;
- the dev tools in requirements-dev.txt and that their config lives in
  pyproject.toml, which Railway does not use to install;
- the commands to run pytest, ruff check, ruff format and mypy, and the
  two CI jobs that Railway waits for before deploying;
- how to make git blame skip the ruff format commit;
- how to build and run the optional Docker image, for the bot and the
  cron.

docs/index.html (the public page) named the old file too; it now points
to the two new folders.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BaCTodSGnaaRDL7Dtj5aCG
@joaquinmuzzi
joaquinmuzzi merged commit 5a9ba00 into master Oct 19, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant