diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..6f5d1ef956caa347a4cd6494dc99643157440920
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,15 @@
+.git
+.gitignore
+.github
+.venv
+venv
+__pycache__
+*.pyc
+.pytest_cache
+.coverage
+htmlcov
+.vscode
+.idea
+.DS_Store
+Thumbs.db
+frontend/node_modules
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..e05f4ea0dc0ef4a778b65d5478e5b789e998418a
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,53 @@
+# ChessTB Explorer: line-ending / diff attributes
+#
+# Every text file in this repo is normalized to LF, regardless of the
+# committer's or cloner's platform or local `core.autocrlf` setting - the
+# app is meant to run identically on Windows/Linux/macOS, and mixed line
+# endings across files (or within one file after a Windows edit) cause
+# noisy whole-file diffs and spurious merge conflicts for no functional
+# reason. Binary assets are marked explicitly so Git never attempts text
+# normalization or diffing on them.
+
+# Fallback: let Git auto-detect text vs binary for anything not matched
+# below, and normalize any text file's line endings to LF in the
+# repository (working-tree endings still follow core.autocrlf locally).
+* text=auto eol=lf
+
+# --- Source / config / docs - force LF explicitly -------------------------
+*.py text eol=lf
+*.js text eol=lf
+*.mjs text eol=lf
+*.css text eol=lf
+*.html text eol=lf
+*.md text eol=lf
+*.yml text eol=lf
+*.yaml text eol=lf
+*.txt text eol=lf
+*.json text eol=lf
+*.svg text eol=lf
+.gitignore text eol=lf
+.gitattributes text eol=lf
+LICENSE text eol=lf
+
+# --- Binary assets - never touch, never diff as text -----------------------
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.woff2 binary
+*.woff binary
+*.ttf binary
+*.ico binary
+
+# --- Vendored third-party code - exclude from GitHub's language stats and
+# from generated-diff/review noise; these files are never hand-edited here,
+# treated as vendored files and excluded from generated-diff noise.
+# See THIRD_PARTY_LICENSES.md for what's vendored and why.
+frontend/src/vendor/** linguist-vendored
+frontend/src/assets/fonts/** linguist-vendored
+
+# --- Generated build output - not hand-edited; excluded from language
+# stats and review diffs. static/dist/ is rebuilt from frontend/src/
+# by `vite build` (see README.md's "Frontend build"); package-lock.json is
+# written by npm.
+static/dist/** linguist-generated
+frontend/package-lock.json linguist-generated
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..b1cb57395c3215358d3c0aab4ff0a58493b7ee80
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,21 @@
+# Local environment files: this project doesn't use one (config.py reads
+# its two secrets, ADMIN_TOKEN and FLASK_SECRET_KEY, directly from the
+# process environment rather than a .env file - see config.py's "Admin"
+# section), but this stays as a no-cost safety net in case one is ever
+# added locally.
+.env
+
+# Python
+__pycache__/
+*.pyc
+.venv/
+venv/
+.pytest_cache/
+.coverage
+htmlcov/
+
+# Editors / OS
+.vscode/
+.idea/
+.DS_Store
+Thumbs.db
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..8aceff5f5d2f6f93e06e006556cb9e2a8006774f
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,41 @@
+FROM python:3.11-slim
+
+# Git is required because requirements.txt installs
+# noobpwnftw/python-chess directly from GitHub.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends git \
+ && rm -rf /var/lib/apt/lists/*
+
+# Run as a non-root user rather than the image's default root. UID 1000 has
+# no special meaning to Render (it just needs to own /app below); it
+# matches Hugging Face Docker Spaces' convention, so the same image also
+# runs there.
+RUN useradd -m -u 1000 user
+
+WORKDIR /app
+
+# Install Python dependencies first so Docker can cache this layer.
+COPY --chown=user requirements.txt /app/requirements.txt
+
+RUN pip install --no-cache-dir --upgrade pip \
+ && pip install --no-cache-dir -r /app/requirements.txt
+
+# Copy the actual application.
+COPY --chown=user . /app
+
+USER user
+
+ENV HOME=/home/user
+ENV PATH=/home/user/.local/bin:$PATH
+ENV PYTHONUNBUFFERED=1
+
+# Purely informational -- config.py's PORT reads the platform's own PORT
+# environment variable at runtime (falling back to 7860 only when it's
+# unset) and that's the port actually bound, regardless of this EXPOSE
+# value. Render assigns and injects PORT itself (see render.yaml /
+# README.md "Deploying to Render"), so nothing needs to change here to
+# match it; 7860 is the default for a local `docker run` with no PORT set,
+# and for Hugging Face Docker Spaces, which expects 7860 specifically.
+EXPOSE 7860
+
+CMD ["python", "app.py"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..c7bf8858e14c0b61748781a4292f0e792644027a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,937 @@
+---
+title: ChessTB Explorer
+emoji: ♟️
+colorFrom: green
+colorTo: blue
+sdk: docker
+pinned: true
+app_port: 7860
+license: gpl-3.0
+short_description: "Interactive tablebase probing: WDL/DTZ/DTC/DTM/DTM50"
+---
+
+# ChessTB Explorer ♟️
+
+Interactive tablebase probing interface with WDL/DTZ/DTC/DTM/DTM50 metrics.
+
+This Hugging Face Space is deployed from
+[PunisherChess/ChessTB-Explorer-Render](https://github.com/PunisherChess/ChessTB-Explorer-Render)
+at commit `4969e401fa41ef1b86458cac4b6a31f9b11e08d0`.
+The original authors' license and third-party notices are retained.
+
+The application probes the public `chesstb/chesstb` bucket over HTTP byte
+ranges, using the explorer's existing bounded page cache. Sources are
+searched per table with raw generator output under `full/` preferred over
+shipping tables at the bucket root. Castling materials use `full/castling/`
+and `castling/`, respectively.
+Availability of each metric depends on the published tables for that material.
+
+`ADMIN_TOKEN` and `FLASK_SECRET_KEY` are configured as Space secrets.
+The probing library follows the maintained `add-chesstb-tablebases` branch
+of `noobpwnftw/python-chess`.
+
+[](https://chesstb-explorer-render.onrender.com)
+
+A single-page web application for exploring **ChessTB** chess endgame
+tablebases. Paste or build any position on an interactive board and
+instantly see every legal move ranked by **Distance to Zeroing (DTZ)**,
+**Distance to Conversion (DTC)**, **Distance to Mate (DTM)**, and **DTM
+under the 50-move rule (DTM50)** - straight from the tablebase, with no
+chess engine involved.
+
+The backend is a small Flask application that probes the tablebase through
+a modified fork of [`python-chess`](https://github.com/noobpwnftw/python-chess/tree/add-chesstb-tablebases)
+(the `chess.chesstb` module - see [Installation](#installation)). The frontend is
+a React app built around
+[Chessground](https://github.com/lichess-org/chessground) (lichess.org's
+board component) and [chessops](https://github.com/niklasf/chessops) for
+move generation/validation, supporting both Standard chess and Chess960
+(Fischer Random).
+
+> This tool only *displays* tablebase results - it does not generate,
+> verify, or ship any tablebase data itself. See
+> [Getting the tablebase files](#getting-the-tablebase-files) below.
+
+> The probe endpoints are unauthenticated by design - evaluating a
+> position is this app's public functionality. The `/admin` cache
+> dashboard is gated behind `ADMIN_TOKEN`, a secret configured by the deployment
+> (see [Security notes](#security-notes)).
+
+---
+
+## Features
+
+- **Interactive board**: drag-and-drop moves, click-to-place pieces from
+ the spare-piece trays, pawn promotion dialog, board flip (orientation
+ persisted locally across visits), undo/redo.
+- **Chess960 (Fischer Random) support**: a **Chess960 Mode** switch in
+ the settings panel changes castling interpretation without altering the
+ current board position: dragging a king onto its own rook castles the
+ Chess960 way, and X-FEN/Shredder-FEN rook-file castling-rights letters
+ (e.g. `HAha`) are accepted in the FEN box. Carried through the shared
+ URL (`&variant=chess960`), the saved in-progress game, and PGN
+ import/export (`[Variant "Chess960"]`). Off by default.
+- **Lock**: a padlock button beside the FEN box that restricts board
+ interaction to legal moves only: dragging, click-to-move, and the
+ spare-piece trays are limited to the side to move's legal destinations,
+ and off-board drops are disabled. Unlocked by default; a manual toggle
+ is remembered locally across visits. Auto-play also engages Lock for
+ the duration of a run (unless already locked by hand), and disables the
+ padlock button until the run stops.
+- **Four ranked move tables side by side**: DTZ, DTC, DTM, and DTM50
+ columns, each independently sorted best-move-first. Exact metric ties
+ prefer immediate checkmate, then use SAN order with promotions along
+ the same path ordered queen, rook, bishop, knight. A better-scoring
+ underpromotion still ranks first. Includes:
+ - score text colour-coded by outcome (win / cursed win / draw /
+ blessed loss / loss)
+ - a **warning dot** on any move flagged cursed win or blessed loss,
+ with a hover tooltip explaining the 50-move-rule nuance; a DTZ score
+ that may still be a ply off after the moves are cross-checked shows a
+ second tooltip line
+ - an **info dot** on a draw by insufficient material, keeping the score
+ text itself reading as a plain "Draw"
+ - dot messages on touch or pen input: tapping a dot shows its tooltip
+ text as a notice and does not play the move
+ - an outcome summary (wins / draws / losses / unknown) across legal moves,
+ respecting the halfmove clock and 50-move rule. It uses DTM50 outcomes,
+ or DTC when DTM50 is unavailable. Without either, clock-independent
+ draws, cursed wins and blessed losses count as draws; unresolved
+ wins/losses count as unknown.
+ - an optional pinned **Root Row** above rank 1, showing the current
+ position's own score for each metric as a reference point - toggled
+ from the settings panel (**Show Root Row**, off by default) and
+ persisted locally
+- **Best-move arrows**: the top DTZ, DTC, DTM, and DTM50 moves are drawn
+ as colour-coded arrows directly on the board.
+- **Auto-play**: automatically plays the best move for any of the four
+ metrics on a timer. The per-move delay
+ is set from the settings panel (**Autoplay Delay**, 0s–2.5s in 50ms
+ steps, 1.25s by default). The countdown starts after the current
+ position's tablebase results are displayed, giving you the full delay
+ to read them before the next move. A metric's button is disabled when its
+ table isn't present for the current material, or when the position is
+ already a draw.
+- **PGN import/export**: paste a PGN to load its full move tree, including
+ variations, at the starting position. Step through it or click any move
+ in the PGN panel, or download the current game as a PGN file.
+- **CSV export** of the current move table, including the Root Row line
+ ahead of rank 1 when that setting is on.
+- **Move-list / PGN panel** with full undo/redo and click-to-jump - jumping
+ to an earlier point in the line re-uses the cached probe instead of
+ re-querying the tablebase.
+- **Shareable positions**: the FEN (and, in Chess960 Mode, the active
+ variant) is written to the URL hash on every move, so a link to the
+ page reproduces the exact position and ruleset.
+- **Session persistence**: the in-progress game (not just the position)
+ survives a trip to the admin dashboard and back.
+- **Board and piece set**: Libre Brown board, CBurnett piece set.
+- **Streaming probes**: `/probe/stream` reports progress via
+ Server-Sent Events while child positions are being probed, so the UI
+ shows a live progress bar instead of a blank pause on slower lookups.
+- **Hover pre-fetch**: hovering a move in the table warms the cache for
+ the resulting position before selection.
+- **Admin cache dashboard** (`/admin`, behind `ADMIN_TOKEN`) - live
+ hit-rate stats for both LRU caches, thread-pool configuration, and a
+ one-click cache-clear button.
+- **Machine-readable API**: the full HTTP API is described by an OpenAPI
+ 3.0 document served at `/openapi.yaml`.
+- **Keyboard shortcuts**: `Enter` Apply, `F` Flip, `C` Clear, `←`/`→`
+ Back/Forward. The Board Settings panel lists them on devices with hover.
+
+---
+
+## Architecture at a glance
+
+```
+Browser (React app - see frontend/)
+ ├─ engine/board.js - chessops-backed position/rules state, chessground
+ │ wrapper (drag/drop, history, arrows), active variant
+ ├─ engine/tablebase.js - talks to /probe/stream, exposes results as state
+ ├─ engine/theme.js - board/piece-set theming
+ ├─ hooks/useExplorer.js - FEN box, PGN, auto-play, settings, keyboard shortcuts
+ └─ components/ - the rendered page (board, results table, PGN panel, dialogs)
+ │ HTTP (JSON) / SSE (text/event-stream) - {fen, variant}
+ ▼
+Flask app (app.py)
+ ├─ /probe, /probe/stream - evaluate a FEN under a variant, rank every legal move
+ ├─ /admin, /admin/cache/* - cache dashboard + stats API
+ └─ /openapi.yaml - API specification
+ │
+ ▼
+tablebase_router.py - searches TABLEBASE_PATH in order for every material,
+including castling positions and recursive dependencies
+ │
+ ▼
+chesstb.open_tablebase(...) per source (noobpwnftw's modified python-chess fork)
+ │
+ ▼
+ChessTB tablebase files - local disk, or a remote http(s) URL (probed
+in place over byte ranges by default, or downloaded and cached to local
+disk per material - see remote/remote_direct.py, remote/remote_fallback.py,
+and "Getting the tablebase files" below)
+```
+
+The React app is built with Vite into `static/dist/` (`app.js`,
+`app.css`), which the Flask template loads as same-origin assets, as the
+Content-Security-Policy (`script-src 'self'`) requires. See
+[Frontend build](#frontend-build) below.
+
+This covers the main explorer page's (`index.html`) module graph - see
+[Project structure](#project-structure) below for the complete file set,
+including `admin.js` (the `/admin` dashboard's client script, a plain
+server-rendered page with no build step).
+
+The Python modules and the frontend `engine/` modules carry a file-level
+docstring/header comment describing their responsibilities, and the
+move-ranking algorithm itself - including
+its treatment of the 50-move rule - is documented inline in `app.py`
+above `evaluate_all_moves()` and the `_effective_move_wdl`/
+`_effective_distance`/`_order_rank` helpers it calls.
+
+---
+
+## Frontend build
+
+The explorer page is a React app (`frontend/`) built with Vite into
+`static/dist/`, which the Flask app serves alongside its own
+static assets. The build output is checked in, so running the app needs
+no frontend server or build step. Rebuild after changing anything under
+`frontend/src/`:
+
+```bash
+cd frontend
+npm ci
+npm run build # writes static/dist/app.js, app.css, admin.css, fonts/
+```
+
+`frontend/src/engine/` and `frontend/src/vendor/` hold the position/rules
+engine (chessops + Chessground) and the tablebase client, consumed by
+the React components in `frontend/src/components/`. Shared UI primitives
+(`Icon`, `Button`, `Segmented`, `Panel`) are in `frontend/src/components/ui/`.
+Piece SVGs and the piece-set stylesheet are in `static/` and are linked
+directly from the page template.
+
+### Styling
+
+Stylesheets are in `frontend/src/styles/` and are bundled by Vite into
+`static/dist/app.css` (explorer page) and `static/dist/admin.css` (`/admin`).
+`tokens.css` defines the colour, type, spacing, radius, elevation, motion,
+and control-size custom properties; other files reference them instead of
+literal values. Files are imported into the `reset`, `vendor`, and `app`
+cascade layers by `index.css` and `admin.css`.
+
+| Token group | Custom properties |
+|---|---|
+| Type scale | `--text-xs` 12 px, `--text-sm` 13 px, `--text-md` 14 px, `--text-lg` 16 px, `--text-xl` 20 px |
+| Spacing | `--space-1` to `--space-6` (4 px to 32 px) |
+| Controls | `--control-h`, `--control-h-sm` (44 px on touch-primary devices) |
+| Board | `--board-light`, `--board-dark`, `--board-highlight`, read by `engine/theme.js` |
+
+Sizes are authored in `rem`, so the large-screen root font size scaling
+applies to all text and controls.
+
+### Page layout
+
+| Viewport | Layout |
+|---|---|
+| Above 1180 px | Three-column CSS grid (board, results, PGN). The results and PGN columns take the board column's height and scroll internally. |
+| 768 to 1180 px | Board row above a results and PGN row; the page scrolls. |
+| Below 768 px | Three horizontally swipeable screens (board, results, PGN) with a bottom navigation bar (`ScreenNav`). Header and navigation heights include the device safe-area insets, and screen heights use `dvh`. The header shows the subtitle below the title, and the board is sized to the visible height so the whole board screen fits. |
+
+The side-to-move toggle and the board form one group (`.board-group`) as wide
+as the board, with a fixed small gap between them at every screen size. Free
+vertical space in the board column sits above the group.
+
+The results panel is a `results` size container. At 49 rem wide and above it
+shows the four metric columns; below that it shows one metric at a time,
+selected with the metric tabs, regardless of viewport width. The desktop
+layout reserves 50 rem for this panel before growing the board, so the
+four-metric view can appear as soon as the three columns fit. The results
+table is a fixed header table above a scrolling body table, so the scrollbar
+starts at the first moves row. The body reserves no scrollbar gutter: while
+its rows overflow, its table is widened by the scrollbar's measured width, so
+columns keep the header's position and width whether or not a scrollbar shows.
+The PGN move-number column width is set by `--pgn-rank-w` in `tokens.css`.
+
+### Display scaling
+
+Sizing is CSS-only and is defined in `frontend/src/styles/layout.css`.
+
+- **Text:** above 1180 px, the root font size of the explorer page
+ (`html.explorer`) is 100% of the browser default up to a 1536 x 780 window
+ and rises to at most 125% (20 px), following the window's width and
+ height. Browser zoom and the browser default font size apply.
+- **Board:** above 1180 px, `--board-size` fills the window height in
+ multiples of 8 px, from 20.5 rem up to `--board-size-max` (720 px, defined
+ in `tokens.css`), and leaves at least 40 rem for the results table. The
+ left column is as wide as the board, so it is capped at 720 px as well.
+ The width the board column does not use goes to the results column, so
+ the total content width stays constant.
+- **Tablet layout:** at 1180 px and below, the root font size is the
+ browser default and `--board-size` is `--board-size-cap`, defined in
+ `tokens.css` as
+ `min(720px, clamp(18.75rem, min(23.4375vw, 41.6667vh), 31.5rem))`.
+- **Phone layout:** below 768 px, `--board-size` is the smaller of
+ `--board-size-cap` (`min(360px, 88vw)` up to 480 px wide) and the height
+ that remains after the header, bottom navigation, and the controls
+ above the board, with a floor of 14 rem. The board screen therefore
+ fits the visible height regardless of browser toolbar size. Below the
+ floor, the screen scrolls from its top.
+- `--board-fit-h` includes the fixed height above the board in the left
+ column and requires an update when that height changes. This applies to
+ both the desktop definition in `layout.css` and the phone definition in
+ `responsive.css`.
+- `html.explorer` is set in `templates/index.html` and `frontend/index.html`.
+ `/admin` does not use it.
+
+---
+
+## Prerequisites
+
+- **Python 3.10+**
+- **Git**, available on `PATH` - `pip install -r requirements.txt` fetches the
+ `python-chess` fork directly from GitHub (`chess @ git+https://...`),
+ which requires `git` to be installed even though the package itself is
+ Python.
+- **A ChessTB tablebase directory or URL**: either a local directory on
+ disk, or an `http(s)://` base URL serving the same layout remotely with
+ no local download (see [Getting the tablebase files](#getting-the-tablebase-files)).
+ The app starts without one, but every probe will fail until
+ `TABLEBASE_PATH` points at the required sources. See
+ [Configuration reference](#configuration-reference).
+- A modern browser (the frontend uses `fetch`, `ReadableStream`, and CSS
+ container queries).
+
+---
+
+## Installation
+
+1. **Create and activate a virtual environment:**
+
+ ```bash
+ python -m venv .venv
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
+ ```
+
+2. **Install dependencies:**
+
+ ```bash
+ pip install -r requirements.txt
+ ```
+
+ This pulls in the **modified `python-chess` fork** (not the plain
+ PyPI `chess` package; see the comments in `requirements.txt` for why
+ that distinction matters).
+
+3. **Get the tablebase files**: see the next section. When using the
+ remote (no-download) option requires no fetch; continue to step 4 and
+ point `TABLEBASE_PATH` at the URL.
+
+4. **Configure `config.py`**: open it and set `TABLEBASE_PATH` to the
+ directory (or URL) from step 3:
+
+ ```python
+ TABLEBASE_PATH = "/data/chesstb"
+ ```
+
+ or, for the remote option:
+
+ ```python
+ TABLEBASE_PATH = "https://huggingface.co/buckets/chesstb/chesstb/resolve"
+ ```
+
+ This alone covers every piece count. See
+ [Getting the tablebase files](#getting-the-tablebase-files) for
+ the ordered source list, which includes shipping tables for both ordinary
+ and castling materials.
+
+ Every other setting in `config.py` has a default and a comment
+ explaining what it does - see
+ [Configuration reference](#configuration-reference) for the complete
+ list. Edit the values directly. To enable the header's source repository button,
+ set `SOURCE_REPOSITORY_URL` there too.
+
+5. **Run the app:**
+
+ ```bash
+ python app.py
+ ```
+
+ By default (`DEBUG = False` in `config.py`) this serves the app via
+ **waitress**, a production-grade pure-Python WSGI server - see
+ [Running in production](#running-in-production) below. Set
+ `DEBUG = True` in `config.py` to use Flask's development server
+ (auto-reload, interactive debugger) for local development.
+
+6. Open **http://127.0.0.1:7860** in a browser.
+
+ The built frontend (`static/dist/`) is checked in; see
+ [Frontend build](#frontend-build) when changing `frontend/src/`.
+
+---
+
+## Getting the tablebase files
+
+Where the tablebase *data* lives is a separate question from where this
+*app* runs - Option A below points `TABLEBASE_PATH` at a plain
+`http(s)://` URL, so it works identically regardless of which platform
+serves the app itself (Render, Hugging Face Spaces, a local machine,
+etc.); `remote/remote_source.py` speaks plain HTTP byte-range requests,
+nothing more, and has no dependency on any one host. See
+[Deploying to Render](#deploying-to-render) for the app side of that
+distinction.
+
+ChessTB tablebase files are available two ways:
+
+### Option A: Remote, no local download (recommended)
+
+Tables are available in the [ChessTB bucket](https://huggingface.co/buckets/chesstb/chesstb).
+Shipping tables are grouped by metric; raw generator output is under `full/`.
+Both use `castling/` for tables with castling rights.
+WDL/DTZ cover 3–8 pieces; DTC/DTM/DTM50 cover 3–6 pieces.
+
+Set `TABLEBASE_PATH` to the bucket root:
+
+```python
+TABLEBASE_PATH = "https://huggingface.co/buckets/chesstb/chesstb/resolve"
+```
+
+The explorer prefers raw generator output under `full/`, falls back to
+shipping tables, and selects `castling/` paths automatically, including
+for recursive dependencies. This applies to Standard chess and Chess960.
+Local roots use the same layout. An explicit list of source directories
+is also supported.
+
+`REMOTE_MODE` selects the remote access mode, which stays fixed for the
+life of the process:
+
+- **`"direct"` (default)**: `remote/remote_direct.py` probes the remote
+ tables **in place**, fetching only the `REMOTE_PAGE_SIZE_BYTES`-sized
+ byte ranges each probe reads and keeping them in an in-memory
+ LRU bounded by `REMOTE_PAGE_CACHE_BYTES`. Nothing is written to disk.
+ This uses `chess.chesstb`'s table-source seam
+ (`Tablebase.WDL_FILE` / `_TableFile._open_source`), which the pinned
+ fork (see `requirements.txt`) provides.
+- **`"download"`**: `remote/remote_fallback.py` fetches each table
+ **in full** the first time a probe touches its material and caches it
+ in a temporary local directory (bounded by
+ `REMOTE_PAGE_CACHE_BYTES` as an on-disk budget, evicting
+ least-recently-used files, removed entirely when the app stops). Every
+ probe after the first is then a local mmap read.
+
+`"direct"` is the better default for browsing across many materials, which
+is what this app does. `"download"` is preferable when a long session
+repeatedly probes a small set of materials, or on a high-latency link: a
+ChessTB probe is not a narrow read - a dropped-frame table is reconstructed by walking
+its children, and pawn positions reach promotion sub-tables - so one cold
+probe can open several materials and issue several fetches against each.
+That is also why `REMOTE_PAGE_SIZE_BYTES` should stay large. See each
+module's docstring for the full design.
+
+Both remote modes cache successful signed CDN redirects until 60 seconds
+before expiry, allowing subsequent byte-range reads to bypass the resolver.
+A failed cached URL is retried through the original URL to obtain a fresh
+redirect. Resolver and CDN connection pools stay open for reuse.
+Complete cached responses are returned immediately by `/probe/stream`,
+without rebuilding the board or queuing child probes. Queued child work is
+cancelled when a stream disconnects or its pre-warm deadline expires;
+already running probes can finish and warm the shared cache.
+Table contents and paths are assumed to remain fixed; existence
+and size metadata stay cached for the process lifetime, including missing
+files. Restart the app after adding or moving tables.
+
+Remote access suits a machine without a couple of terabytes of local disk
+for the full tablebase set. Its costs are probe latency on first touch of
+any given material (depending on the connection to the CDN), temporary
+local disk usage in `"download"` mode, and the requirement of a network
+connection. Remote access uses the `requests` package (see
+`requirements.txt`).
+
+### Option B: Local directory, over FTP
+
+The same tables are also distributed over FTP for a fully local, offline
+setup:
+
+```
+ftp://chessdb:chessdb@ftp.chessdb.cn/pub/chesstb/
+```
+
+Any FTP client works, for example:
+
+```bash
+# lftp
+lftp -e "mirror --parallel=4 /pub/chesstb/ /data/chesstb; quit" \
+ ftp://chessdb:chessdb@ftp.chessdb.cn
+
+# curl (single file)
+curl "ftp://chessdb:chessdb@ftp.chessdb.cn/pub/chesstb/" -o
+```
+
+Tablebase sets are large and grow quickly with piece count - check
+available disk space before mirroring the full archive, and consider
+mirroring only the required subsets (piece counts). Point
+`TABLEBASE_PATH` at the selected directory.
+
+---
+
+Regardless of how it is configured, if `TABLEBASE_PATH` is unset, missing/unreachable, or
+points at a location with no usable tables, the app still starts (with a
+warning in the logs) - every `/probe` request will then return an error,
+and `/health` reports `"degraded"`.
+
+---
+
+## Configuration reference
+
+All configuration lives in **`config.py`**, as plain Python values. Open
+it and edit the settings directly - each one has a comment above it
+explaining what it does. The table below is the complete reference.
+
+The defaults target a single process on Hugging Face CPU Basic
+(2 vCPU, 16 GB RAM). The decoded-block cache has a shared 512 MiB
+budget, and each of the four default remote sources has a 2 GiB page
+cache budget, totaling 8.5 GiB of byte-cache budgets. Caches fill on
+demand; this is not a cap on process memory. Root-response and child-probe
+caches are limited by entry count, with memory use depending on response
+size. The remaining RAM accommodates those results, table/index metadata,
+Python object overhead, and active requests. Revisit the budgets if you
+add remote sources or run multiple application processes.
+
+| Setting | Default | Description |
+|-----------------------------|-------------------|-------------|
+| `TABLEBASE_PATH` | Public bucket root (also readable from a `TABLEBASE_PATH` env var) | Directory containing the ChessTB tablebase files, **or** an `http(s)://` base URL serving the same layout remotely (e.g. a Hugging Face storage bucket - see [Getting the tablebase files](#getting-the-tablebase-files)). Required for probing to work. A list of directories and URLs, tried left-to-right (a hybrid source), is accepted as a literal in `config.py` only. On Render, set this from the service's Environment tab (or `render.yaml`'s prompt) instead of editing the file. |
+| `DEBUG` | `False` | `True` runs `app.py` via Flask's own dev server (auto-reload, detailed tracebacks) instead of waitress. Leave `False` - which serves via waitress - for anything reachable from another machine. See [Running in production](#running-in-production). |
+| `HOST` | `"0.0.0.0"` | Interface the server (waitress, or the dev server if `DEBUG = True`) binds to. |
+| `PORT` | `7860` (also readable from a `PORT` env var) | Port the server listens on. Render injects its own `PORT` at deploy time and this picks it up automatically - nothing to set for a Render deployment. |
+| `WAITRESS_THREADS` | `4` | Worker threads in waitress's request-handling pool. Only relevant when `DEBUG = False`. Needs to be more than 1 so a long-lived `/probe/stream` connection can't block other requests. |
+| `PROBE_THREADS` | `2` | Worker threads in the probe thread pool for evaluating a position's legal moves in parallel. Set an explicit integer to match the host's CPU count, or `None` to scale automatically (`min(16, cpu*2)`). |
+| `PROBE_PARALLEL_THRESHOLD` | `4` | Minimum number of child positions before probing switches from sequential to the thread pool. |
+| `PROBE_TIMEOUT_SECS` | `30` | Wall-clock timeout for each probe phase. `/probe` gives the root probe and the child-move batch independent budgets, so worst-case `/probe` latency can approach `2 × PROBE_TIMEOUT_SECS`. Also bounds how long a request waits on another thread's in-flight probe of the same FEN before giving up with a retryable `probe_timeout` error. |
+| `EVALUATE_CACHE_SIZE` | `16384` | Max entries in the root-FEN result cache (full JSON responses). |
+| `PROBE_CACHE_SIZE` | `262144` | Max entries in the child-position probe cache (raw `chess.chesstb.ProbeResult` objects - WDL/DTZ/DTC/DTM/DTM50 together). |
+| `BLOCK_CACHE_BYTES` | `536870912` (512 MiB) | Size, in bytes, of `chesstb`'s own internal cache of decoded/decompressed tablebase blocks (shared across the WDL/DTZ/DTC/DTM/DTM50 tables). Raising this trades RAM for fewer repeated disk reads/HTTP fetches + decompressions across a session - most worthwhile when `PROBE_PARALLEL_THRESHOLD` is set high enough that probing runs mostly serially. |
+| `REMOTE_MODE` | `"direct"` | **Remote tablebase entries only.** `"direct"` probes the remote tables in place over byte ranges (nothing written to disk); `"download"` fetches each table in full on first touch and caches it on local disk. See [Getting the tablebase files](#getting-the-tablebase-files). |
+| `REMOTE_PAGE_CACHE_BYTES` | `2147483648` (2 GiB) | **Remote tablebase entries only.** Soft budget, in bytes, per remote source in `TABLEBASE_PATH`, shared across that source's tables: the in-memory page cache in `"direct"` mode, the on-disk cache of whole downloaded files in `"download"` mode. See [Getting the tablebase files](#getting-the-tablebase-files). |
+| `REMOTE_PAGE_SIZE_BYTES` | `262144` (256 KiB) | **Remote tablebase entries only.** Size, in bytes, of one page. In `"direct"` mode this is the granularity of every fetch, so it trades over-fetching against round trips per probe; in `"download"` mode it is only the chunk size used while streaming a full file down. |
+| `REMOTE_TIMEOUT_SECS` | `20` | **Remote tablebase entries only.** Per-HTTP-request timeout for existence/size checks and the download itself. |
+| `REMOTE_MAX_RETRIES` | `3` | **Remote tablebase entries only.** Attempts for a single remote request before it's treated as failed. |
+| `REMOTE_POOL_MAXSIZE` | `None` | **Remote tablebase entries only.** Size of each remote backend's HTTP connection pool. `None` computes `max(PROBE_THREADS * 2, 20)`. |
+| `PROBE_RATE_LIMIT` | `"60 per minute"` | Per-client-IP request limit on `/probe` and `/probe/stream`, using [flask-limiter](https://flask-limiter.readthedocs.io/)'s string syntax. Left empty, rate limiting is disabled entirely. See [Security notes](#security-notes). |
+| `ADMIN_LOGIN_RATE_LIMIT` | `"5 per minute"` | Per-client-IP request limit on `/admin/login`, same string syntax as `PROBE_RATE_LIMIT`, applied independently of it. Covers both failed and successful login attempts. Left empty, login attempts are not rate limited. See [Security notes](#security-notes). |
+| `PREFETCH_RATE_LIMIT` | `"30 per minute"` | Per-client-IP request limit for hover prefetch requests marked with `X-Prefetch: 1`. Left empty, prefetch requests share `PROBE_RATE_LIMIT`. See [Security notes](#security-notes). |
+| `TRUSTED_PROXY_COUNT` | `1` (also readable from a `TRUSTED_PROXY_COUNT` env var) | Number of trusted reverse-proxy hops in front of this app. In production this configures [waitress's own `trusted_proxy_count`](https://docs.pylonsproject.org/projects/waitress/en/stable/proxy-headers.html) (waitress parses `X-Forwarded-For`/`X-Forwarded-Proto` and corrects `REMOTE_ADDR`/`wsgi.url_scheme` itself, ahead of Flask); [Werkzeug's `ProxyFix`](https://werkzeug.palletsprojects.com/en/latest/middleware/proxy_fix/) makes the same correction for the `DEBUG = True` dev-server path, which doesn't run under waitress. Both rate limiters key on the corrected address, and `request.scheme`/`request.is_secure` read the corrected scheme. `1` matches this project's own `render.yaml` topology (Render's edge/load-balancer, once). Set it to match the deployment's reverse-proxy chain, or set it to `0` for a deployment with no reverse proxy in front of it at all. See [Security notes](#security-notes). |
+| `ADMIN_TOKEN` | `""` (from `ADMIN_TOKEN` env var) | Shared secret required to reach `/admin` and `/admin/cache/*`. Read from the environment rather than hardcoded, so it can be set as a platform secret. Left unset, admin routes respond `503` rather than running unprotected. See [Security notes](#security-notes). |
+| `FLASK_SECRET_KEY` | `""` (from `FLASK_SECRET_KEY` env var) | Key used to sign the admin session cookie. Read from the environment for the same reason as `ADMIN_TOKEN`. Left unset, a random key is generated at process startup instead, so every restart requires logging in again. |
+| `SESSION_COOKIE_SECURE` | `False` (also readable from a `SESSION_COOKIE_SECURE` env var, `"true"`/anything else) | Whether the admin session cookie set by `/admin/login` requires HTTPS. Independent of `DEBUG`. Defaults `False` to match a plain-HTTP local installation; set to `"true"` for any deployment the browser reaches over HTTPS (including behind a TLS-terminating reverse proxy such as Render's - `render.yaml` already sets this explicitly for that deployment). See [Security notes](#security-notes). |
+| `SOURCE_REPOSITORY_URL` | `""` (also readable from a `SOURCE_REPOSITORY_URL` env var) | Repository URL for the source repository button shown in the header of every page. Edited directly like any other non-secret value here, or set as an env var on a given deployment. Left empty, the button is omitted. |
+
+Invalid values (wrong type, out of range) cause the app to log an error
+and exit at startup rather than run with a silently-wrong configuration.
+
+---
+
+## Running in production
+
+`python app.py` serves the app via **[waitress](https://docs.pylonsproject.org/projects/waitress/)**,
+a production-grade, pure-Python WSGI server, whenever `DEBUG` in
+`config.py` is `False` (the default) - no separate `gunicorn`/`waitress`
+command or extra process is needed on top of the app itself. Setting
+`DEBUG = True` in `config.py` switches `app.py` over to Flask's own dev
+server instead (auto-reload + interactive debugger), which is meant for
+local development only and should not be used for anything reachable
+from another machine.
+
+```bash
+# Production (default): DEBUG = False in config.py: serves via waitress
+python app.py
+
+# Local development: set DEBUG = True in config.py first, then run the
+# same command: Flask dev server, auto-reload + debugger
+python app.py
+```
+
+- `HOST` / `PORT` control the interface and port waitress binds to, same
+ as for the dev server. `PORT` is also readable from a `PORT`
+ environment variable (see [Configuration reference](#configuration-reference)),
+ which is what lets the same image bind correctly on Render - or any
+ other platform that assigns the port at deploy time - with no edits.
+- `WAITRESS_THREADS` (default `4`) sizes waitress's own pool of
+ request-handling threads. This needs to be more than 1 for the same
+ reason the dev server needs `threaded=True`: `/probe/stream` holds a
+ connection open via Server-Sent Events for the whole duration of a
+ probe, and a single-threaded server would let that one connection block
+ every other request - including the browser's own concurrent requests
+ for CSS/JS/piece images on first page load. It's independent of
+ `PROBE_THREADS`, which sizes the thread pool used internally to
+ parallelise tablebase probing rather than to serve HTTP requests.
+- `TRUSTED_PROXY_COUNT` (default `1`) configures waitress's own
+ `trusted_proxy_count`, so `request.remote_addr` and `request.scheme`
+ reflect the real client IP and scheme behind Render's edge/load-balancer
+ rather than that proxy's own address/hop - see
+ [Security notes](#security-notes).
+- Waitress handles `/probe/stream`'s streamed response natively; no
+ additional configuration is needed for SSE to work correctly.
+- The probe endpoints are unauthenticated by design; only `/admin` and
+ `/admin/cache/*` require a credential (see
+ [Security notes](#security-notes)).
+
+---
+
+## Deploying to Render
+
+This project deploys to [Render](https://render.com) as a single Docker
+web service, built straight from this GitHub repository. Render watches
+the connected branch and rebuilds/redeploys automatically on every push.
+
+There are two ways to set it up:
+
+### Option 1: Blueprint (`render.yaml`, recommended)
+
+This repository ships a [`render.yaml`](render.yaml) at its root
+describing the service (Docker runtime, health check, environment
+variables). Render finds it automatically:
+
+1. Push this repository to GitHub.
+2. In the [Render Dashboard](https://dashboard.render.com), click
+ **New → Blueprint** and connect the repo.
+3. Render reads `render.yaml` and requests the one setting required
+ before the first deploy can run: **`TABLEBASE_PATH`** - the
+ `http(s)://` base URL of the remote tablebase (see
+ [Getting the tablebase files](#getting-the-tablebase-files)).
+ `ADMIN_TOKEN` and `FLASK_SECRET_KEY` are generated automatically.
+4. Click **Apply** / **Create**. Render builds the image from this
+ repo's `Dockerfile` and deploys it.
+
+Every subsequent push to the connected branch redeploys automatically.
+To change `TABLEBASE_PATH`, `ADMIN_TOKEN`, or any other setting later,
+edit it from the service's **Environment** tab in the Render Dashboard;
+see [Configuration reference](#configuration-reference) for which
+settings are env-overridable this way versus which live only in
+`config.py`.
+
+### Option 2: Manual Web Service (no `render.yaml`)
+
+The service can also be configured manually without the Blueprint file:
+
+1. Push this repository to GitHub.
+2. In the Render Dashboard, click **New → Web Service** and connect the
+ repo.
+3. Set **Runtime** to **Docker** (Render should detect the `Dockerfile`
+ at the repo root automatically).
+4. Under **Environment**, add:
+ - `TABLEBASE_PATH`: required; same as Option 1 above.
+ - `ADMIN_TOKEN`: optional but recommended; any secret string, or
+ use Render's "Generate" button. While it is unset, `/admin`
+ responds `503`.
+ - `FLASK_SECRET_KEY`: optional; when omitted, a random key is
+ generated at process startup and admin sessions don't survive a
+ restart.
+ - `SESSION_COOKIE_SECURE`: set to `true`. Render always terminates
+ TLS at its edge, so the browser reaches this deployment over HTTPS
+ even though the app itself just speaks plain HTTP to Render's
+ proxy; `config.py`'s own default (`false`) is tuned for a local
+ plain-HTTP installation instead. (Option 1's `render.yaml` sets
+ this automatically - it is a manual step here because Option 2
+ skips that file.)
+ - `SOURCE_REPOSITORY_URL`: optional; the repository URL, which enables the
+ header's source repository button.
+ - Leave `PORT` alone - Render sets it itself, and `config.py` already
+ reads it (see [Configuration reference](#configuration-reference)).
+5. Under **Health Check Path**, set `/health` (matches the route in
+ `app.py`; Render won't mark a deploy healthy until this returns `200`,
+ which itself only happens once the sources in `TABLEBASE_PATH` have
+ opened successfully).
+6. Click **Create Web Service**.
+
+### Choosing a plan
+
+Probing is CPU-bound (block decompression on every request), so a
+dedicated vCPU - Render's **Starter** tier or above - gives lower probe
+latency than the **Free** tier's shared/limited CPU. Free works
+for casual or low-traffic use; the service spins down after inactivity
+(a slow first request after waking up) and probes are slower under load. Either way, `REMOTE_MODE = "direct"` (the default)
+means no persistent disk is needed regardless of plan - see
+`config.py`'s "Remote (URL) tablebase entries only" section and
+[Getting the tablebase files](#getting-the-tablebase-files).
+
+---
+
+## Usage guide
+
+- **Set a position**: type or paste a FEN into the FEN box and press
+ `Enter` or **Apply**. The move rankings and best-move arrows update
+ automatically. The castling-availability field accepts `-` or any
+ combination of `K`, `Q`, `k`, `q` (each requiring a matching king and
+ rook on their home squares); in **Chess960 Mode** it additionally
+ accepts X-FEN/Shredder-FEN rook-file letters (`a`-`h` / `A`-`H`). A
+ position with a castling right is evaluated the same as any other,
+ reported as not covered if the loaded tablebase set has no table for it
+ (see `TABLEBASE_PATH` in
+ [Configuration reference](#configuration-reference)).
+- **Chess960 (Fischer Random)**: toggle **Chess960 Mode** in the settings
+ panel to switch castling interpretation. This does not move any pieces
+ or randomize a new starting position - it only changes how castling
+ moves/rights on the *current* board are interpreted, and drops the
+ current move line the same way a board edit does (a line built under
+ one variant isn't reinterpreted as the other). With it on, drag a king
+ onto its own rook to castle; the destination square and resulting rook
+ position follow standard Chess960 rules regardless of where the king
+ and rook started. The setting is carried in the shared URL
+ (`&variant=chess960`), the saved in-progress game, and PGN
+ import/export (a `[Variant "Chess960"]` header).
+- **Edit the board directly**: drag pieces around the board, drag a piece
+ off the board to remove it, or click a spare piece in either tray and
+ then click a square to place it (click again / press `Esc` to cancel).
+ Board edits reset the current move line the same way **Clear** does.
+- **Lock the board**: click the padlock button beside the FEN box to
+ restrict drag-and-drop, click-to-move, and the spare-piece trays to
+ legal moves for the side to move; the button turns gold while active.
+ Click again to unlock. The choice is remembered locally across visits.
+ Starting auto-play locks the board automatically for the run (unless
+ already locked) and disables the padlock button until it stops.
+- **Play moves**: click any move in one of the four ranked tables to
+ play it, or drag a piece on the board through a legal move.
+- **Navigate history**: the Undo/Redo arrow buttons or `←`/`→`, or click
+ any move in the PGN panel to jump straight to that point in the line.
+- **Auto-play**: click the ▶ button above the DTZ, DTC, DTM, or DTM50
+ columns
+ to have the app play that metric's best move on a timer (delay set by
+ **Autoplay Delay** in settings, 1.25s by default); click again (the
+ button shows ■ while running) to stop. Any manual navigation stops auto-play.
+- **Import/export a game**: **Import** in the PGN panel opens a dialog to
+ paste PGN text. **Import Game** loads the full game and its variations
+ into the PGN panel, starting before the first move; **Export**
+ downloads the full game and its variations as `chesstb_game.pgn` with
+ standard headers.
+- **Export the move table**: the **CSV** button downloads the current
+ DTZ/DTC/DTM/DTM50 rankings as a CSV file.
+- **Share a position**: the URL updates live with `#fen=...`; sending
+ that link reproduces the exact position.
+- **Change settings**: the ⚙ button in the header opens a **Show Root
+ Row** switch for the results table, a **Chess960 Mode** switch, and an
+ **Autoplay Delay** slider; the choices are persisted across visits.
+- **Admin dashboard**: the gauge icon in the header opens `/admin`, prompting for the
+ `ADMIN_TOKEN` on first visit, then showing live hit-rate stats for both
+ caches and the thread-pool configuration, auto-refreshing every 5
+ seconds.
+
+---
+
+## API
+
+The full HTTP API - `/probe`, `/probe/stream`, `/health`,
+`/admin/cache/stats`, `/admin/cache/clear`, `/admin/login`,
+`/admin/logout` - is documented as an OpenAPI 3.0 specification served
+live by the running app at:
+
+```
+http://127.0.0.1:7860/openapi.yaml
+```
+
+`openapi.yaml` documents every endpoint's request/response shapes; the
+ranking algorithm behind `moves_dtz` / `moves_dtc` / `moves_dtm` /
+`moves_dtm50` is documented inline in `app.py`'s own module docstring and
+its `evaluate_all_moves()` function. `/admin/cache/*` require an
+`Authorization: Bearer ` header or an authenticated session
+cookie from `/admin/login` - see [Security notes](#security-notes).
+
+Quick example:
+
+```bash
+curl -X POST http://127.0.0.1:7860/probe \
+ -H "Content-Type: application/json" \
+ -d '{"fen": "4k3/8/8/8/8/8/8/4K2R w - - 0 1"}'
+```
+
+`variant` is optional and defaults to `"standard"` when omitted. It is
+never inferred from the FEN itself - the orthodox starting array is
+itself a legal Chess960 starting position, so the same FEN text is
+ambiguous without it:
+
+```bash
+curl -X POST http://127.0.0.1:7860/probe \
+ -H "Content-Type: application/json" \
+ -d '{"fen": "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1", "variant": "chess960"}'
+```
+
+---
+
+## Project structure
+
+```
+.
+├── LICENSE # GPL-3.0-or-later license text for this project
+├── THIRD_PARTY_LICENSES.md # Licenses and attributions for bundled third-party code, fonts, and the piece set
+├── Dockerfile # Container build used for Render (and any other Docker host)
+├── render.yaml # Render Blueprint: service definition, health check, env vars
+├── app.py # Flask backend: routes, probing, caching
+├── config.py # All configuration, as plain Python values - see "Configuration reference"
+├── openapi.yaml # OpenAPI 3.0 specification, served at /openapi.yaml
+├── requirements.txt
+├── README.md
+├── .gitattributes, .gitignore, .dockerignore
+├── tablebase_router.py # Ordered local/remote source lookup for every material
+├── tablebase_opening.py # Per-material table-opening lock policy, shared by tablebase_router.py and both remote backends
+├── dtz_anchor.py # Resolves rounded DTZ values by cross-checking the moves of a position
+├── remote/
+│ ├── remote_source.py # Generic HTTP byte-range client shared by both remote backends - see its own module docstring
+│ ├── remote_direct.py # REMOTE_MODE="direct": probe remote tables in place over byte ranges - see its own module docstring
+│ └── remote_fallback.py # REMOTE_MODE="download": whole-file download, cached to local disk on first touch - see its own module docstring
+├── templates/
+│ ├── index.html # Main explorer UI - mounts the React app (see frontend/)
+│ └── admin.html # Cache dashboard
+├── frontend/ # React app for the explorer page - see "Frontend build"
+│ ├── package.json, package-lock.json
+│ ├── vite.config.js # Builds into ../static/dist with fixed filenames (no cache-busting hash)
+│ ├── index.html, admin.html # Build entries (script and stylesheet)
+│ └── src/
+│ ├── main.jsx, App.jsx
+│ ├── engine/ # Position/rules engine and tablebase client (chessops + Chessground)
+│ ├── vendor/ # Vendored Chessground (script and base stylesheet) + chessops, bundled by the build
+│ ├── hooks/useExplorer.js # FEN box, PGN, auto-play, settings, keyboard shortcuts
+│ ├── components/ # Board, results table, PGN panel, dialogs, settings panel
+│ │ └── ui/ # Icon, Button, Segmented, Panel
+│ ├── styles/ # Tokens, base, layout, component and chess stylesheets - see "Styling"
+│ └── assets/fonts/ # Inter and JetBrains Mono (woff2)
+└── static/
+ ├── dist/ # Built frontend (see "Frontend build"): app.js, app.css, admin.css, fonts/
+ ├── css/
+ │ └── pieces-cburnett.css # Piece-set stylesheet linked by templates/index.html
+ ├── js/
+ │ └── admin.js # Admin dashboard client
+ └── pieces/cburnett/ # Piece-set SVGs
+```
+
+---
+
+## Security notes
+
+- The `/probe` and `/probe/stream` endpoints are intentionally
+ unauthenticated - evaluating a chess position is this app's public,
+ core functionality. `/admin` and `/admin/cache/*` are gated behind
+ `ADMIN_TOKEN` (see below); every other route requires no credential.
+- **Rate limiting** on `/probe` and `/probe/stream` is controlled by
+ `PROBE_RATE_LIMIT`, and on `/admin/login` separately by
+ `ADMIN_LOGIN_RATE_LIMIT` (both in `config.py`'s "Rate limiting"
+ section), each applied per client IP via
+ [flask-limiter](https://flask-limiter.readthedocs.io/). A client over
+ either limit gets a `429` with a JSON error body. `PROBE_RATE_LIMIT`'s
+ default, `"60 per minute"`, covers normal browsing and
+ autoplay at its default delay - raise it if legitimate autoplay at a
+ fast delay setting gets throttled, lower it if the deployment sees
+ abuse, or set either limit to `""` to disable it entirely.
+ `ADMIN_LOGIN_RATE_LIMIT` defaults to `"5 per minute"`, tight enough to
+ slow down repeated `ADMIN_TOKEN` guesses. Both limiters key on
+ `request.remote_addr` as corrected by `TRUSTED_PROXY_COUNT` (see
+ below) and their state lives in-process (`memory://`), which is
+ sufficient for a single-container deployment (e.g. one Render Web
+ Service instance) but isn't shared across multiple replicas.
+- **`TRUSTED_PROXY_COUNT`** (`config.py`'s "Rate limiting" section) is
+ what `request.remote_addr`, and therefore both rate limiters above,
+ is corrected against, so it reads the real client IP from
+ `X-Forwarded-For` rather than the address of the reverse proxy
+ in front of this app. The same setting also governs whether
+ `X-Forwarded-Proto` is trusted, correcting `request.scheme` /
+ `request.is_secure` (and any externally-generated URL) when TLS
+ terminates at that reverse proxy rather than at this app itself. In
+ production (`DEBUG = False`) this configures [waitress's own `trusted_proxy_count`](https://docs.pylonsproject.org/projects/waitress/en/stable/proxy-headers.html):
+ waitress parses both headers and corrects `REMOTE_ADDR`/`wsgi.url_scheme`
+ itself, before Flask ever sees the request, so it takes priority here.
+ [Werkzeug's `ProxyFix`](https://werkzeug.palletsprojects.com/en/latest/middleware/proxy_fix/)
+ makes the equivalent correction for the `DEBUG = True` Flask-dev-server
+ path, which doesn't run under waitress at all. Defaults to `1`,
+ matching this project's own `render.yaml` topology; set it to match
+ the deployment if that differs, or to `0` for a deployment with no
+ reverse proxy in front of it at all.
+- **Admin access** is controlled by `ADMIN_TOKEN` (`config.py`'s "Admin"
+ section), read from the environment rather than hardcoded - set it as
+ a platform secret (e.g. a Render environment variable, generated
+ automatically by `render.yaml`'s `generateValue: true`) rather than
+ committing it. Visiting `/admin` with no active session shows a login
+ form; a correct token there starts a signed, `HttpOnly`,
+ `SameSite=Lax` session cookie (`Secure` too, where configured - see
+ `SESSION_COOKIE_SECURE` below). API clients can instead send
+ `Authorization: Bearer ` directly, no session needed.
+ Token comparison uses `hmac.compare_digest` (constant-time, resistant
+ to timing attacks). Leaving `ADMIN_TOKEN` unset does **not** open the
+ admin panel to everyone - every admin route responds `503` instead.
+- **`SESSION_COOKIE_SECURE`** (`config.py`'s "Admin" section) controls
+ whether the admin session cookie above requires HTTPS, independently
+ of `DEBUG` - `DEBUG` is a development/runtime behavior switch, not a
+ reliable indicator of the deployment's transport security, so
+ `DEBUG = False` alone does not imply HTTPS is in front of this
+ app. Read from a `SESSION_COOKIE_SECURE` env var (`"true"` or anything
+ else, case-insensitive), defaulting `False` to match this project's own
+ plain-HTTP local installation - a browser won't send a
+ `Secure` cookie back over a plain HTTP connection, so `/admin/login`
+ would otherwise appear to succeed while every subsequent authenticated
+ `/admin/*` request came back `401`. Set to `"true"` for any deployment
+ the browser reaches over HTTPS (including behind a TLS-terminating
+ reverse proxy - the browser's own connection is what the `Secure`
+ attribute governs, not the internal hop between the proxy and this
+ process); `render.yaml` already sets this explicitly for the Render
+ deployment it configures, since Render always terminates TLS at its
+ edge.
+- The app serves via **waitress**, a production-grade WSGI server, by
+ default (`DEBUG = False` in `config.py`) - see [Running in production](#running-in-production).
+ Only set `DEBUG = True` (which switches to Flask's own dev server) for
+ local development, never for anything reachable from another machine.
+- A `Content-Security-Policy` is set on every response: scripts and fonts
+ are restricted to `'self'` (no inline scripts, no third-party sources);
+ styles allow `'self'` plus `'unsafe-inline'` (needed for inline
+ `style` attributes set by the React app and in `admin.html`); images
+ allow `'self'` plus `data:`; `connect-src`/`default-src` are `'self'`
+ too, so `fetch`/SSE calls can only reach this same origin. `object-src`,
+ `base-uri`, and `form-action` are locked to `'none'`/`'self'`/`'self'`,
+ and `frame-ancestors 'self' https://huggingface.co` allows the Hugging
+ Face Space page to embed the app. `X-Content-Type-Options:
+ nosniff` and `Referrer-Policy: strict-origin-when-cross-origin` are set
+ too. Request bodies are capped at 4 KB.
+- `config.py` itself holds no secrets - `ADMIN_TOKEN` and
+ `FLASK_SECRET_KEY` are the only two secrets, and they are read only from
+ the environment so the file stays safe to commit as-is. Every other
+ setting is a non-sensitive value.
+
+---
+
+## Troubleshooting
+
+| Symptom | Likely cause |
+|---|---|
+| Every probe returns "Position not covered by the loaded tablebase." | Check `TABLEBASE_PATH` and the startup logs. Set the tablebase root; `full/` and `castling/` directories are resolved automatically. For an explicit source list, include every required directory. |
+| A FEN is rejected with "Invalid castling availability" | The submitted castling-availability field is something other than `-` or a combination of `K`, `Q`, `k`, `q` (or, in Chess960 Mode, rook-file letters `a`-`h`/`A`-`H`), or names a castling right without a matching king and rook on the board. |
+| A FEN with `a`-`h`/`A`-`H` castling-rights letters is rejected even though the position looks fine | Those letters are only accepted with **Chess960 Mode** on (settings panel, or `variant: "chess960"` on the API) - Standard mode only accepts `K`, `Q`, `k`, `q`, matching Standard chess's fixed castling-rook squares. |
+| Dragging a king onto its own rook doesn't castle | **Chess960 Mode** is off - enable it in the settings panel (or send `variant: "chess960"` on the API) for Chess960-style king-onto-rook castling; in Standard mode a king can only reach its rook's square by regular king movement. |
+| `/health` returns `503 degraded` | The tablebase failed to open - check `TABLEBASE_PATH` and file permissions. |
+| `ModuleNotFoundError: No module named 'chess.chesstb'` | Plain PyPI `chess` was installed instead of the fork. Re-run `pip install -r requirements.txt` and confirm it pulled `chess` from `noobpwnftw/python-chess` (the `add-chesstb-tablebases` branch) rather than plain PyPI `chess` - see the note at the top of `requirements.txt`. |
+| `ModuleNotFoundError: No module named 'config'` | `config.py` is missing from alongside `app.py`. It ships with the repository - if it was deleted or moved, restore it from the repo (or re-clone) and re-apply any edits, such as `TABLEBASE_PATH`. |
+| App logs `Configuration error: ...` and exits immediately | A value in `config.py` is the wrong type or out of range for that setting (e.g. a string where an integer is expected, or a negative cache size) - the error message names which setting and why. Fix it in `config.py` and re-run `python app.py`. |
+| Admin dashboard panels stuck on "Loading…" | Check the browser console for a CSP violation and verify that the app is running and reachable at the `/admin` URL. |
+| A drag, drop, or spare-piece placement on the board is silently rejected | The board is Locked - the padlock button beside the FEN box is highlighted gold. Lock restricts board interaction to legal moves and disables the spare-piece trays and off-board drops; click the padlock again to unlock and edit freely. |
+| Probing feels slow on positions with many legal moves, or doesn't scale with `PROBE_THREADS` | Confirm `lz4` is installed (`pip show lz4`, or `python -c "import lz4"`) - without it, `chess.chesstb`'s block decompression runs in pure Python and holds the GIL, so `PROBE_THREADS` can't achieve real parallelism. `pip install lz4` (already in `requirements.txt`) and restart. Otherwise, tune `PROBE_THREADS`, `PROBE_PARALLEL_THRESHOLD`, and `PROBE_TIMEOUT_SECS` in `config.py`. Note that `tablebase_router.py` guards each material's first open with a lock keyed by `(kind, material)`, so two threads racing to open the *same* never-before-seen material collapse onto one read, while distinct materials of the same kind open concurrently. If any configured tier uses `REMOTE_MODE="download"`, opens fall back to one lock shared per kind, so several distinct never-before-seen materials of that kind then open one at a time instead - either way, this only affects the very first probe against any given material. |
+| `ModuleNotFoundError: No module named 'waitress'` | The active environment's dependencies are out of date - re-run `pip install -r requirements.txt` to pick up `waitress`. `app.py` imports it unconditionally at the top of the file, before `config.DEBUG` is even read, so setting `DEBUG = True` does **not** avoid this - waitress has to be installed either way. |
+| Every probe on a remote `TABLEBASE_PATH` returns "Position not covered..." or `/health` is `degraded` | Confirm the URL is reachable and correct (try opening `TABLEBASE_PATH/wdl/KQK.lzw` - or any small material's `.lzw` - directly in a browser). Check the startup log's "TABLEBASE_PATH opened remotely at: ..." line (or a warning in its place) for the actual failure. |
+| A probe occasionally returns `503` with `error_code: "probe_timeout"` | Another concurrent request was already probing the same position and didn't finish within `PROBE_TIMEOUT_SECS`. This is transient and retryable - the original probe has usually landed in the child-probe cache before a retry, so the retry is inexpensive. Frequent occurrences suggest raising `PROBE_TIMEOUT_SECS`, or that a slow remote `TABLEBASE_PATH` is the underlying bottleneck. |
+| Remote probing feels slow, or repeated probes against the same material keep hitting the network | Check `REMOTE_TIMEOUT_SECS`/`REMOTE_MAX_RETRIES` aren't causing retries on a slow link, and consider raising `REMOTE_PAGE_CACHE_BYTES` - a too-small budget evicts cached pages (`"direct"`) or downloaded files (`"download"`) before later probes can reuse them. `GET /admin/cache/stats` surfaces this per tier as `tablebase_cache..remote_page_cache` or `.remote_disk_cache` respectively. On a high-latency link also try raising `REMOTE_PAGE_SIZE_BYTES`, or `REMOTE_MODE = "download"`. See [Configuration reference](#configuration-reference). |
+| On Render, the deploy never goes live / stays stuck "deploying" | Render's health check (`healthCheckPath: /health` in `render.yaml`, or the equivalent field on a manually-created service - see [Deploying to Render](#deploying-to-render)) only passes once `/health` returns `200`, which itself requires the sources in `TABLEBASE_PATH` to have opened successfully. Check the service's **Logs** tab for the same "opened remotely at: ..." / warning line described above. |
+| On Render, the service responds but the page never loads / connection refused | Typically a `PORT` mismatch. Confirm `config.py` reads `PORT` from the environment (see [Configuration reference](#configuration-reference)) and that nothing else in a custom start command overrides `HOST`/`PORT`. |
+
+---
+
+## Credits
+
+- Tablebase data & format: [ChessTB / chessdb.cn](https://www.chessdb.cn/)
+- Tablebase probing support: [noobpwnftw/python-chess (`add-chesstb-tablebases` branch)](https://github.com/noobpwnftw/python-chess/tree/add-chesstb-tablebases), a fork of [niklasf/python-chess](https://github.com/niklasf/python-chess)
+- Remote (URL) tablebase support for the fork's `chess.chesstb` module - see `remote/remote_source.py`, `remote/remote_direct.py` and `remote/remote_fallback.py`
+- Board UI: [Chessground](https://github.com/lichess-org/chessground)
+- Move generation/validation on the client, for both Standard chess and
+ Chess960: [chessops](https://github.com/niklasf/chessops)
+- Production WSGI server: [waitress](https://docs.pylonsproject.org/projects/waitress/)
+- Piece set: [cburnett](https://github.com/lichess-org/lila/blob/master/COPYING.md), a commonly-used community set found in most web chess UIs.
+
+## License
+
+ChessTB Explorer is licensed under `GPL-3.0-or-later`; see [`LICENSE`](LICENSE).
+Bundled third-party components and their licenses are listed in
+[`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md
new file mode 100644
index 0000000000000000000000000000000000000000..056b5767ee477fc636711dc4d8646cc21a048af3
--- /dev/null
+++ b/THIRD_PARTY_LICENSES.md
@@ -0,0 +1,133 @@
+# Third-Party Notices
+
+This project bundles or depends on the third-party components listed
+below. Each entry states the component, version, SPDX license
+identifier, and source. This document is provided for attribution and
+license-compliance purposes only and does not constitute legal advice;
+consult qualified counsel before distributing, selling, or publicly
+deploying this software.
+
+Every file in this repository not listed in the tables below - including
+`app.py`, `config.py`, `dtz_anchor.py`, `tablebase_opening.py`,
+`tablebase_router.py`, `static/js/admin.js`,
+`static/css/*.css`, `templates/*.html`,
+`frontend/src/engine/`, `frontend/src/hooks/`, `frontend/src/components/`,
+`frontend/src/styles/`, `frontend/src/*.jsx`, and `remote/`, `Dockerfile`, `render.yaml`,
+`.dockerignore`, `requirements.txt`, and `openapi.yaml` - is original and
+licensed under the terms in [`LICENSE`](LICENSE) (`GPL-3.0-or-later`).
+
+## Summary
+
+| Component | Version | License (SPDX) | Category |
+|---|---|---|---|
+| [React](https://github.com/facebook/react) | 18.3.1 | `MIT` | Frontend |
+| [React DOM](https://github.com/facebook/react) | 18.3.1 | `MIT` | Frontend |
+| [Scheduler](https://github.com/facebook/react) | 0.23.2 | `MIT` | Frontend |
+| [Chessground](https://github.com/lichess-org/chessground) | 10.1.1 | `GPL-3.0-or-later` | Frontend |
+| [chessops](https://github.com/niklasf/chessops) | 0.15.1 | `GPL-3.0-or-later` | Frontend |
+| [@badrap/result](https://github.com/badrap/result) | 0.3.1 | `MIT` | Frontend |
+| [Inter](https://rsms.me/inter/) | — | `OFL-1.1` | Font |
+| [JetBrains Mono](https://www.jetbrains.com/lp/mono/) | — | `OFL-1.1` | Font |
+| cburnett piece set | — | `GPL-2.0-or-later` | Asset |
+| [chess](https://github.com/noobpwnftw/python-chess) (`add-chesstb-tablebases` fork) | latest on branch | `GPL-3.0-or-later` | Python |
+| [Flask](https://github.com/pallets/flask) | `>=3.0,<4.0` | `BSD-3-Clause` | Python |
+| [lz4](https://github.com/python-lz4/python-lz4) | `>=4.0,<5.0` | `BSD-3-Clause` | Python |
+| [waitress](https://github.com/Pylons/waitress) | `>=3.0,<4.0` | `ZPL-2.1` | Python |
+| [requests](https://github.com/psf/requests) | `>=2.31,<3.0` | `Apache-2.0` | Python |
+| [Flask-Limiter](https://github.com/alisaifee/flask-limiter) | `>=4.0,<5.0` | `MIT` | Python |
+
+## Notices
+
+This project is licensed as a whole under `GPL-3.0-or-later` - see
+[`LICENSE`](LICENSE).
+
+The following bundled components carry their own `GPL` license terms:
+
+- **`chess` / `chess.chesstb`** (`GPL-3.0-or-later`): imported
+ directly by `app.py`.
+- **Chessground** (`GPL-3.0-or-later`): vendored in
+ `frontend/src/vendor/`, bundled into `static/dist/app.js`, and served
+ to every client.
+- **chessops** (`GPL-3.0-or-later`): vendored in
+ `frontend/src/vendor/chessops/`, bundled into `static/dist/app.js`,
+ and served to every client.
+- **cburnett piece set** (`GPL-2.0-or-later`): bundled in
+ `static/pieces/cburnett/` and served to every client.
+
+React, React DOM, Scheduler, and `@badrap/result` (`MIT`) are also
+bundled into `static/dist/app.js` - see
+[React / build dependencies](#react--build-dependencies-frontend) below.
+
+## Frontend engine libraries: `frontend/src/vendor/`
+
+| File | Component | Version | License | Source |
+|---|---|---|---|---|
+| `chessground.min.js` | Chessground | 10.1.1 | `GPL-3.0-or-later` | [lichess-org/chessground](https://github.com/lichess-org/chessground) |
+| `chessops/*.js` (excl. `badrap-result.js`) | chessops | 0.15.1 | `GPL-3.0-or-later` | [niklasf/chessops](https://github.com/niklasf/chessops) |
+| `chessops/badrap-result.js` | @badrap/result | 0.3.1 | `MIT` | [badrap/result](https://github.com/badrap/result) |
+| `chessground.base.css` | Chessground stylesheet | 10.1.1 | `GPL-3.0-or-later` | [lichess-org/chessground](https://github.com/lichess-org/chessground) |
+
+`frontend/src/vendor/` holds the pinned ESM distribution and its
+`@badrap/result` runtime dependency; `vite build` bundles them into
+`static/dist/app.js` together with the frontend's own code. They are
+not fetched from a CDN at request time. `chessground.base.css` is
+bundled into `static/dist/app.css`.
+
+## React / build dependencies: `frontend/`
+
+| Component | Version | License | Source |
+|---|---|---|---|
+| React | 18.3.1 | `MIT` | [facebook/react](https://github.com/facebook/react) |
+| React DOM | 18.3.1 | `MIT` | [facebook/react](https://github.com/facebook/react) |
+| Scheduler | 0.23.2 | `MIT` | [facebook/react](https://github.com/facebook/react) (React DOM's runtime dependency) |
+
+Installed via `npm install` from `frontend/package.json` and bundled
+into `static/dist/app.js` by `vite build`; not present anywhere else in
+the served application. Vite and `@vitejs/plugin-react` are build-time
+only and are not distributed to clients.
+
+## Fonts: `frontend/src/assets/fonts/`
+
+| File(s) | Typeface | License | Author |
+|---|---|---|---|
+| `Inter-Regular.woff2`, `Inter-Medium.woff2`, `Inter-SemiBold.woff2` | Inter | `OFL-1.1` | [Rasmus Andersson](https://rsms.me/inter/) |
+| `JetBrainsMono-Regular.woff2`, `JetBrainsMono-Medium.woff2` | JetBrains Mono | `OFL-1.1` | [JetBrains](https://www.jetbrains.com/lp/mono/) |
+
+The build copies the fonts to `static/dist/fonts/`.
+
+## Chess piece set: `static/pieces/` (via lichess.org)
+
+| Directory | License | Author | Source |
+|---|---|---|---|
+| `cburnett/` | `GPL-2.0-or-later` | Colin M.L. Burnett | [lila COPYING.md](https://github.com/lichess-org/lila/blob/master/COPYING.md) |
+
+## Python dependencies: `requirements.txt`
+
+| Package | License | Notes |
+|---|---|---|
+| `chess` (installed from `noobpwnftw/python-chess`, `add-chesstb-tablebases` branch) | `GPL-3.0-or-later` | Fork of [niklasf/python-chess](https://github.com/niklasf/python-chess). Both the base `chess` package and `chess.chesstb` are imported directly by `app.py`. |
+| Flask | `BSD-3-Clause` | [pallets/flask](https://github.com/pallets/flask) |
+| lz4 | `BSD-3-Clause` | [python-lz4/python-lz4](https://github.com/python-lz4/python-lz4). Optional but recommended: `chess.chesstb` picks it up itself at import time to accelerate its own block decompression, falling back to its own pure-Python decoder if not present. `app.py` doesn't import or reference it directly. |
+| waitress | `ZPL-2.1` | [Pylons/waitress](https://github.com/Pylons/waitress) |
+| requests | `Apache-2.0` | [psf/requests](https://github.com/psf/requests). Imported only when `TABLEBASE_PATH` is a remote `http(s)://` URL (`remote/remote_source.py`, `remote/remote_fallback.py`). |
+| Flask-Limiter | `MIT` | [alisaifee/flask-limiter](https://github.com/alisaifee/flask-limiter). Provides the per-IP rate limiting on `/probe` and `/probe/stream` - see `config.py`'s `PROBE_RATE_LIMIT`. |
+
+## License texts
+
+| SPDX identifier | Text |
+|---|---|
+| `GPL-3.0-or-later` | |
+| `GPL-2.0-or-later` | |
+| `BSD-2-Clause` | |
+| `BSD-3-Clause` | |
+| `OFL-1.1` | |
+| `ZPL-2.1` | |
+| `Apache-2.0` | |
+| `MIT` | |
+
+## Tablebase data
+
+Not covered by this document. This project only displays results from
+ChessTB tablebase files supplied by the user (see `README.md` →
+"Getting the tablebase files"). No tablebase data is bundled with the
+app.
diff --git a/app.py b/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..d273ec5ec3f4e961803f5bc0b2816f9540910ada
--- /dev/null
+++ b/app.py
@@ -0,0 +1,2048 @@
+"""
+app.py: ChessTB Explorer back-end
+
+A single-file Flask application that probes a ChessTB endgame tablebase
+for a submitted FEN position and returns every legal move ranked by
+Distance to Zeroing (DTZ), Distance to Conversion (DTC), Distance to
+Mate (DTM), and DTM under the 50-move rule (DTM50).
+
+DTC is 50-move-rule-aware in the same way DTM50 is (it is always probed
+at the position's own halfmove clock), but unlike DTM50 it has no
+"flat"/clock-independent sibling column of its own -- there is only ever
+one DTC value for a position. A ``.lzdtc`` table only exists for material
+with at least one pawn; for pawnless material `chess.chesstb` derives an
+equivalent answer from DTZ/WDL instead (see chess.chesstb.ProbeResult),
+so `has_dtc` is False only when a pawnful material's own
+`.lzdtc` file genuinely hasn't been generated/shipped.
+
+Routes
+------
+ POST /probe - evaluate a FEN position (JSON)
+ POST /probe/stream - evaluate with SSE streaming progress
+ GET / - main UI
+ GET /health - readiness check
+ GET /admin - cache dashboard HTML page, or a login form if not authenticated
+ POST /admin/login - start an admin session (JSON {token})
+ POST /admin/logout - end the admin session
+ POST /admin/cache/clear - purge both LRU caches
+ GET /admin/cache/stats - cache hit-rate statistics
+ GET /openapi.yaml - OpenAPI 3.0 specification
+
+/admin and /admin/cache/* require admin authentication -- either a
+session cookie started via /admin/login, or an "Authorization: Bearer
+" header. See config.py's "Admin" section and README.md's
+"Security notes" for how ADMIN_TOKEN is configured.
+
+/probe and /probe/stream are rate-limited per client IP (config.py's
+PROBE_RATE_LIMIT); a client over the limit gets a 429 with a JSON body.
+/admin/login has its own, separate limit (config.py's
+ADMIN_LOGIN_RATE_LIMIT), covering both failed and successful attempts.
+
+Each move entry includes a child_fen so the client can pre-fetch the next
+probe, and each response includes a summary of wins/draws/losses/unknown
+across all legal moves. A position not covered by the loaded tablebase
+raises MissingTableError, which is returned as structured JSON
+({error_code, piece_count}). Root-JSON and child-probe cache sizes are set
+by config.EVALUATE_CACHE_SIZE / config.PROBE_CACHE_SIZE.
+
+Every request to /probe and /probe/stream carries an explicit "variant"
+field ("standard" or "chess960", defaulting to "standard" when omitted)
+alongside "fen" -- the two rulesets are never inferred from a FEN's
+contents, since the orthodox starting arrangement is itself a legal
+Chess960 starting position and would otherwise be ambiguous. A submitted
+FEN's castling-availability field accepts "-" or any combination of "K",
+"Q", "k", "q" for variant="standard", plus rook-file letters ("a"-"h" /
+"A"-"H") for variant="chess960"; a right with no matching king/rook pair
+is rejected as invalid input before the board is ever probed (see
+_validate_and_build_board). A position with castling rights is otherwise
+probed like any other: `chess.chesstb` resolves it when the loaded
+tablebase set carries a table for that material (see config.py's
+TABLEBASE_PATH and tablebase_router.py -- unaffected by variant,
+since a Chess960 board's clean_castling_rights() reports the same way a
+Standard board's does), and reports it as not covered when it doesn't.
+
+Running this file directly (`python app.py`) serves the app via waitress
+(a production-grade WSGI server) by default. Set DEBUG = True in
+config.py to use Flask's own dev server instead (auto-reload +
+interactive debugger) for local development. See README.md
+"Installation" / "Running in production" for details.
+"""
+
+from __future__ import annotations
+
+from collections import OrderedDict, namedtuple
+from concurrent.futures import (
+ ThreadPoolExecutor,
+ wait as futures_wait,
+ ALL_COMPLETED,
+ FIRST_COMPLETED,
+)
+from dataclasses import dataclass
+from flask import (
+ Flask, render_template, request, jsonify, Response,
+ stream_with_context, send_file, session,
+)
+from flask_limiter import Limiter
+from flask_limiter.util import get_remote_address
+from functools import lru_cache, wraps
+from typing import TypedDict
+from waitress import serve as waitress_serve
+from werkzeug.middleware.proxy_fix import ProxyFix
+import atexit
+import chess
+import config
+import dtz_anchor
+import hmac
+import json
+import os
+import re
+import logging
+import secrets
+import tablebase_router
+import threading
+import time
+
+# ── Logging ───────────────────────────────────────────────────────────────────
+
+logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
+log = logging.getLogger(__name__)
+
+
+# ── ChessTB backend ───────────────────────────────────────────────────────────
+
+# chess.chesstb comes from noobpwnftw's add-chesstb-tablebases fork of
+# python-chess (see requirements.txt) - open_tablebase, ProbeResult's raw
+# wdl/dtz/dtc/dtm/dtm50 fields, MissingTableError, and the WIN/CURSED_WIN/
+# DRAW/BLESSED_LOSS/LOSE constants all come from that module.
+import chess.chesstb as chesstb
+
+log.info("chess.chesstb backend: noobpwnftw/python-chess (add-chesstb-tablebases)")
+
+# Remote (HTTP) tablebase support, in two flavours -- config.REMOTE_MODE
+# picks one (see tablebase_router.open_one):
+# remote/remote_direct.py ("direct") probe in place over byte ranges
+# remote/remote_fallback.py ("download") whole-file download, disk-cached
+# See each file's module docstring for the design and the trade-off.
+# looks_like_remote()/RemoteSourceError come from remote/remote_source.py.
+from remote import remote_direct, remote_fallback, remote_source
+
+
+# ── Type aliases ──────────────────────────────────────────────────────────────
+
+class MoveEntry(TypedDict):
+ san: str
+ plies: int
+ order: int # DTC only: pawn pushes still owed before a conversion (0 for every other metric)
+ is_mate: bool
+ outcome: str # "win"|"cursed_win"|"draw"|"blessed_loss"|"loss"|"unknown"|"not_available"
+ available: bool # False when this move's own metric table isn't present (outcome is then "not_available")
+ child_fen: str | None # FEN after this move; None for terminal / unknown
+ draw_reason: str | None # "stalemate"|"insufficient_material"|None
+
+
+class DtzMoveEntry(MoveEntry, total=False):
+ rounded: bool # DTZ rows only, when available: plies may be a ply off
+
+
+@dataclass
+class _DtzMove:
+ row: int # index into the DTZ rows
+ my_wdl: int
+ keeps_class: bool
+ option: dtz_anchor.MoveOption
+
+
+MoveList = list[MoveEntry]
+
+
+# ── Config validation helpers ─────────────────────────────────────────────────
+# Centralise the "read a config.py value, check its type, validate range"
+# pattern that AppConfig.from_config() below needs once per setting.
+
+def _validated_int(name: str, value, *, min_val: int = 1, max_val: int | None = None) -> int:
+ if isinstance(value, str):
+ # PORT and TRUSTED_PROXY_COUNT are the two config.py settings read
+ # as a raw string rather than pre-converted at import time (see
+ # config.py's own comments on each) -- specifically so a bad
+ # value raises here, inside AppConfig.from_config()'s try/except,
+ # rather than as an uncaught ValueError from a bare int() call
+ # during module import, before this module has an exception handler
+ # in place for it.
+ try:
+ value = int(value.strip())
+ except ValueError:
+ raise ValueError(f"config.{name} must be an integer, got {value!r}") from None
+ if not isinstance(value, int) or isinstance(value, bool):
+ raise ValueError(f"config.{name} must be an integer, got {value!r}")
+ if max_val is None:
+ if value < min_val:
+ raise ValueError(f"config.{name} must be >= {min_val}, got {value}")
+ elif not (min_val <= value <= max_val):
+ raise ValueError(f"config.{name} must be {min_val}-{max_val}, got {value}")
+ return value
+
+
+def _validated_float(name: str, value) -> float:
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ raise ValueError(f"config.{name} must be a number, got {value!r}")
+ value = float(value)
+ if value <= 0:
+ raise ValueError(f"config.{name} must be > 0, got {value}")
+ return value
+
+
+def _validated_str(name: str, value) -> str:
+ if not isinstance(value, str):
+ raise ValueError(f"config.{name} must be a string, got {value!r}")
+ return value
+
+
+def _validated_path_spec(name: str, value) -> str | list[str]:
+ """TABLEBASE_PATH: a
+ single path (local directory or http(s):// URL) or a list of them for
+ a hybrid source (see tablebase_router.py). Each list entry must
+ itself be a string -- a nested list isn't a valid hybrid source."""
+ if isinstance(value, str):
+ return value
+ if isinstance(value, (list, tuple)) and all(isinstance(v, str) for v in value):
+ return list(value)
+ raise ValueError(f"config.{name} must be a string or a list of strings, got {value!r}")
+
+
+def _validated_choice(name: str, value, allowed: tuple) -> str:
+ if value not in allowed:
+ raise ValueError(
+ f"config.{name} must be one of {', '.join(map(repr, allowed))}, got {value!r}")
+ return value
+
+
+def _validated_bool(name: str, value) -> bool:
+ if not isinstance(value, bool):
+ raise ValueError(f"config.{name} must be True or False, got {value!r}")
+ return value
+
+
+# ── Validated configuration ───────────────────────────────────────────────────
+
+@dataclass(frozen=True)
+class AppConfig:
+ tablebase_path: str | list[str]
+ probe_threads: int
+ parallel_threshold: int
+ probe_timeout: float
+ host: str
+ port: int
+ evaluate_cache_size: int
+ probe_cache_size: int
+ block_cache_bytes: int
+ debug: bool
+ waitress_threads: int
+ # Only used for an http(s):// URL entry in tablebase_path (see "ChessTB
+ # backend" above and remote/remote_source.py) -- ignored entirely for
+ # a local-directory entry. Bounds an on-disk LRU of whole downloaded
+ # table files cached by remote/remote_fallback.py (see that file's
+ # module docstring for the full design).
+ remote_mode: str
+ remote_page_cache_bytes: int
+ remote_page_size_bytes: int
+ remote_timeout_secs: float
+ remote_max_retries: int
+ remote_pool_maxsize: int
+ admin_token: str
+ secret_key: str
+ source_repository_url: str
+ probe_rate_limit: str
+ prefetch_rate_limit: str
+ admin_login_rate_limit: str
+ trusted_proxy_count: int
+ session_cookie_secure: bool
+ # Hard-coded limit, not one of config.py's settings -- kept as a
+ # dataclass field (rather than a bare module constant) so it reads
+ # alongside every other request-validation knob above.
+ max_fen_length: int = 100
+
+ @classmethod
+ def from_config(cls) -> "AppConfig":
+ # PROBE_THREADS is the one setting with a computed (not literal)
+ # default, so a None left in config.py falls back to a
+ # CPU-count-based figure instead of going through _validated_int.
+ threads = (
+ _validated_int("PROBE_THREADS", config.PROBE_THREADS)
+ if config.PROBE_THREADS is not None
+ else min(16, (os.cpu_count() or 4) * 2)
+ )
+ # Same "None means auto" shape as PROBE_THREADS above, computed
+ # from it: a connection pool smaller than the probe thread count
+ # gives up connection reuse for whichever requests land once the
+ # pool is exhausted (see remote/remote_source.py).
+ pool_maxsize = (
+ _validated_int("REMOTE_POOL_MAXSIZE", config.REMOTE_POOL_MAXSIZE)
+ if config.REMOTE_POOL_MAXSIZE is not None
+ else max(threads * 2, 20)
+ )
+
+ return cls(
+ tablebase_path=_validated_path_spec("TABLEBASE_PATH", config.TABLEBASE_PATH),
+ probe_threads=threads,
+ parallel_threshold=_validated_int("PROBE_PARALLEL_THRESHOLD", config.PROBE_PARALLEL_THRESHOLD),
+ probe_timeout=_validated_float("PROBE_TIMEOUT_SECS", config.PROBE_TIMEOUT_SECS),
+ host=_validated_str("HOST", config.HOST),
+ port=_validated_int("PORT", config.PORT, max_val=65535),
+ evaluate_cache_size=_validated_int("EVALUATE_CACHE_SIZE", config.EVALUATE_CACHE_SIZE),
+ probe_cache_size=_validated_int("PROBE_CACHE_SIZE", config.PROBE_CACHE_SIZE),
+ block_cache_bytes=_validated_int("BLOCK_CACHE_BYTES", config.BLOCK_CACHE_BYTES),
+ # DEBUG also selects the server used by
+ # `if __name__ == "__main__"` below: the Flask dev server when
+ # True, waitress otherwise (see README.md "Running in production").
+ debug=_validated_bool("DEBUG", config.DEBUG),
+ waitress_threads=_validated_int("WAITRESS_THREADS", config.WAITRESS_THREADS),
+ remote_mode=_validated_choice("REMOTE_MODE", config.REMOTE_MODE, ("direct", "download")),
+ remote_page_cache_bytes=_validated_int(
+ "REMOTE_PAGE_CACHE_BYTES", config.REMOTE_PAGE_CACHE_BYTES),
+ remote_page_size_bytes=_validated_int(
+ "REMOTE_PAGE_SIZE_BYTES", config.REMOTE_PAGE_SIZE_BYTES),
+ remote_timeout_secs=_validated_float("REMOTE_TIMEOUT_SECS", config.REMOTE_TIMEOUT_SECS),
+ remote_max_retries=_validated_int("REMOTE_MAX_RETRIES", config.REMOTE_MAX_RETRIES),
+ remote_pool_maxsize=pool_maxsize,
+ admin_token=_validated_str("ADMIN_TOKEN", config.ADMIN_TOKEN),
+ secret_key=_validated_str("FLASK_SECRET_KEY", config.FLASK_SECRET_KEY),
+ source_repository_url=_validated_str("SOURCE_REPOSITORY_URL", config.SOURCE_REPOSITORY_URL),
+ probe_rate_limit=_validated_str("PROBE_RATE_LIMIT", config.PROBE_RATE_LIMIT),
+ prefetch_rate_limit=_validated_str("PREFETCH_RATE_LIMIT", config.PREFETCH_RATE_LIMIT),
+ admin_login_rate_limit=_validated_str("ADMIN_LOGIN_RATE_LIMIT", config.ADMIN_LOGIN_RATE_LIMIT),
+ trusted_proxy_count=_validated_int(
+ "TRUSTED_PROXY_COUNT", config.TRUSTED_PROXY_COUNT, min_val=0, max_val=10),
+ session_cookie_secure=_validated_bool("SESSION_COOKIE_SECURE", config.SESSION_COOKIE_SECURE),
+ )
+
+
+try:
+ cfg = AppConfig.from_config()
+except (ValueError, AttributeError) as e:
+ log.error("Configuration error: %s — fix config.py and restart.", e)
+ raise SystemExit(1) from e
+
+# Exception type to treat as "couldn't reach the remote tablebase" in the
+# /probe and /probe/stream handlers below.
+_REMOTE_SOURCE_ERROR = remote_source.RemoteSourceError
+
+if not cfg.tablebase_path:
+ log.warning("TABLEBASE_PATH is not set — tablebase lookups will fail.")
+
+if not cfg.admin_token:
+ log.warning(
+ "ADMIN_TOKEN is not set — /admin and /admin/cache/* will respond "
+ "503 until it's configured (see config.py's \"Admin\" section)."
+ )
+
+
+# ── Flask app ─────────────────────────────────────────────────────────────────
+
+app = Flask(__name__)
+app.config["MAX_CONTENT_LENGTH"] = 4 * 1024 # 4 KB
+
+# secrets.token_hex(32) generated fresh at process startup when
+# FLASK_SECRET_KEY isn't set (see config.py) -- every admin session is then
+# invalidated by a restart, requiring a new login; it never
+# breaks anything the app itself depends on, since sessions here hold
+# nothing but the admin_ok flag set by /admin/login.
+app.secret_key = cfg.secret_key or secrets.token_hex(32)
+app.config["SESSION_COOKIE_HTTPONLY"] = True
+app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
+# Independent of cfg.debug -- see config.py's SESSION_COOKIE_SECURE for
+# why: DEBUG is a development/runtime behavior switch, not a reliable
+# indicator of whether the browser reaches this deployment over HTTPS.
+app.config["SESSION_COOKIE_SECURE"] = cfg.session_cookie_secure
+
+# Without this, request.remote_addr -- and therefore get_remote_address()
+# below, which keys both rate limiters -- is whichever host made the TCP
+# connection to this process. Behind a reverse proxy (Render's own
+# edge/load-balancer in front of the render.yaml deployment this project
+# ships with, or any other reverse proxy placed in front of it) that's the
+# proxy's own address, not the actual client's, so every client sharing
+# that proxy would collapse onto one rate-limit key. ProxyFix instead
+# trusts exactly cfg.trusted_proxy_count X-Forwarded-For hops closest to
+# this app and reads the real client IP from ahead of them -- set to 0
+# this is a no-op, appropriate only for a deployment with no reverse proxy
+# in front of it at all (an untrusted client's own X-Forwarded-For header
+# would otherwise be trusted, letting it spoof its rate-limit key).
+#
+# x_proto does the equivalent correction for X-Forwarded-Proto, which a
+# TLS-terminating reverse proxy sets to tell this app the scheme the
+# client actually connected with -- without it, request.scheme /
+# request.is_secure (and any URL this app builds with
+# url_for(..., _external=True)) would read as plain http:// even when the
+# client's own connection was https://, since Flask only ever sees the
+# proxy's own (typically-HTTP) hop to this app. Same trusted-hop count as
+# x_for, for the same reason: a value here that doesn't match the real
+# proxy chain either misreads the scheme or lets a client spoof it.
+#
+# This only actually matters for cfg.debug's Flask-dev-server path below --
+# under waitress (cfg.debug False, the production path), waitress parses
+# X-Forwarded-For and corrects REMOTE_ADDR itself before this app ever
+# sees the request, taking priority over -- and making redundant, but
+# harmlessly so -- the correction this makes. See the waitress_serve(...)
+# call below for that side of it.
+if cfg.trusted_proxy_count > 0:
+ app.wsgi_app = ProxyFix(
+ app.wsgi_app, x_for=cfg.trusted_proxy_count, x_proto=cfg.trusted_proxy_count)
+
+
+@app.errorhandler(413)
+def request_too_large(e: Exception) -> tuple:
+ return jsonify({"error": "Request body too large (max 4 KB)."}), 413
+
+
+# ── Rate limiting ────────────────────────────────────────────────────────────
+# Per-IP limits on /probe, /probe/stream (config.py's PROBE_RATE_LIMIT, or
+# PREFETCH_RATE_LIMIT for a request tagged "X-Prefetch: 1" -- see
+# _request_probe_limit below) and, separately, /admin/login (config.py's
+# ADMIN_LOGIN_RATE_LIMIT -- see README.md's "Security notes").
+# default_limits=[] means nothing is limited except the routes explicitly
+# decorated with @_probe_rate_limit / @_admin_login_rate_limit below; the
+# in-memory storage is per-process, which is enough for a single-container
+# deployment but doesn't share state across multiple replicas. key_func
+# reads request.remote_addr, which ProxyFix (see the Flask app section
+# above) has already corrected for cfg.trusted_proxy_count reverse-proxy
+# hops.
+limiter = Limiter(
+ key_func=get_remote_address, app=app, default_limits=[], storage_uri="memory://",
+ headers_enabled=True)
+
+
+def _request_probe_limit() -> str:
+ # X-Prefetch is client-asserted and therefore untrusted as a basis for
+ # relaxing enforcement -- it only ever selects a separate, tighter
+ # budget than the default, never bypasses PROBE_RATE_LIMIT. A request
+ # without the header, or when PREFETCH_RATE_LIMIT is unset, always
+ # falls back to the normal probe budget.
+ if request.headers.get("X-Prefetch") == "1" and cfg.prefetch_rate_limit:
+ return cfg.prefetch_rate_limit
+ return cfg.probe_rate_limit
+
+
+def _probe_rate_limit(view):
+ # A plain pass-through when neither limit is configured, rather than
+ # a zero/near-zero limiter.limit() call, so "disabled" actually means
+ # unlimited rather than "limited to approximately nothing." A
+ # callable limit_value (rather than the plain string
+ # _admin_login_rate_limit below uses) is what lets a single decorator
+ # route a hover-prefetch request to its own, tighter budget -- see
+ # _request_probe_limit above -- flask-limiter re-evaluates it on
+ # every request rather than once at decoration time.
+ if not cfg.probe_rate_limit and not cfg.prefetch_rate_limit:
+ return view
+ return limiter.limit(_request_probe_limit)(view)
+
+
+def _admin_login_rate_limit(view):
+ # Independent of _probe_rate_limit above -- /admin/login is a
+ # brute-forceable shared-secret check, not a CPU-bound probe, so it
+ # gets its own (much tighter) limit rather than reusing or being
+ # covered by PROBE_RATE_LIMIT.
+ if not cfg.admin_login_rate_limit:
+ return view
+ return limiter.limit(cfg.admin_login_rate_limit)(view)
+
+
+@app.errorhandler(429)
+def rate_limit_exceeded(e: Exception) -> tuple:
+ return jsonify({
+ "error": "Too many requests. Please slow down and try again shortly.",
+ }), 429
+
+
+# ── Tablebase + thread pool ───────────────────────────────────────────────────
+# All material, including castling and recursive dependencies, uses the
+# same ordered source list. The adapter shares one decoded-block cache.
+try:
+ _tb_source = tablebase_router.open_many(
+ cfg.tablebase_path, label="TABLEBASE_PATH", cfg=cfg,
+ remote_source=remote_source, remote_direct=remote_direct,
+ remote_download=remote_fallback,
+ )
+except Exception as e:
+ log.warning("Failed to open TABLEBASE_PATH: %s", e)
+ _tb_source = None
+
+TB = (
+ tablebase_router.SourcedTablebase(
+ _tb_source, remote_source=remote_source,
+ block_cache_bytes=cfg.block_cache_bytes,
+ )
+ if _tb_source is not None else None
+)
+
+_executor = ThreadPoolExecutor(max_workers=cfg.probe_threads, thread_name_prefix="tb_probe")
+log.info(
+ "Thread pool: %d workers, parallel_threshold=%d, timeout=%.0fs, "
+ "eval_cache=%d, probe_cache=%d, block_cache_bytes=%d",
+ cfg.probe_threads, cfg.parallel_threshold, cfg.probe_timeout,
+ cfg.evaluate_cache_size, cfg.probe_cache_size, cfg.block_cache_bytes,
+)
+
+
+@atexit.register
+def _close_tb() -> None:
+ try:
+ if TB is not None:
+ TB.close()
+ except Exception as e:
+ log.warning("Error closing tablebase: %s", e)
+
+
+@atexit.register
+def _shutdown_executor() -> None:
+ try:
+ _executor.shutdown(wait=True, cancel_futures=True)
+ except Exception as e:
+ log.warning("Error shutting down thread pool: %s", e)
+
+
+# ── Security headers ──────────────────────────────────────────────────────────
+
+@app.after_request
+def set_security_headers(response: Response) -> Response:
+ # base-uri and form-action are set explicitly since default-src doesn't
+ # cover them; object-src, though covered, is set to 'none' since the app
+ # has no use for